如何在WPF中重构事件



我有多个带有TextChanged事件的文本框绑定到同一处理程序

<TextBox TextChanged="TextBox_TextChanged" />
<TextBox TextChanged="TextBox_TextChanged" />
<TextBox TextChanged="TextBox_TextChanged" />
<TextBox TextChanged="TextBox_TextChanged" />

有什么办法做这样的事吗?

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="TextBox">
            <Setter Property="TextChanged" Value="TextBox_TextChanged" />
         </Style>
    </StackPanel.Resources>
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
</StackPanel>

我知道上面的代码是无效的,但它与我想要实现的类似

如果我没有弄错,您可以将TextBoxBase.TextChanged="TextBox_TextChanged"属性放在所有文本框的公共容器元素上,例如:

<StackPanel TextBoxBase.TextChanged="TextBox_TextChanged">
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
</StackPanel>

如果你想要一种样式:

<Style TargetType="{x:Type TextBox}">
    <EventSetter Event="TextChanged" Handler="TextBox_TextChanged"/>
</Style>

最新更新