【问题标题】:WPF TextBox trigger to clear TextWPF TextBox 触发器以清除文本
【发布时间】:2019-02-19 20:27:03
【问题描述】:

我有很多 TextBox 控件,我正在尝试编写一种样式,清除 Text 属性当控件禁用 . 我不想在代码中包含事件处理程序。

这是我写的:

<Style TargetType="{x:Type TextBox}">                            
 <Style.Triggers>
  <Trigger Property="IsEnabled" Value="False">                                    
   <Setter Property="Text" Value="{x:Null}" />
  </Trigger>                                
 </Style.Triggers>
</Style>

问题在于,如果 TextBox 的定义如下:

<TextBox Text={Binding Whatever} />

然后触发器不起作用(可能是因为它被绑定了) 如何克服这个问题?

【问题讨论】:

    标签: wpf text textbox triggers


    【解决方案1】:

    因为您在 TextBox 中明确设置了 Text,所以样式的触发器无法覆盖它。试试这个:

    <TextBox>
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Text" Value="{Binding Whatever}" />
    
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Text" Value="{x:Null}" /> 
                    </Trigger>
                </Style.Triggers>
            </Style> 
        </TextBox.Style>
    </TextBox>
    

    【讨论】:

    • 我只是想问问。如果我想将此作为样式添加到控件的资源中(因此我不必重复 100 次),是否可以使用 TemplateBinding 之类的东西,或者我是否必须编写一个继承自 TextBox 的自定义控件和在默认模板中使用 TemplateBinding 指定此样式?
    • 只需在 Window 的 Resources 部分定义样式并给它一个 x:Key。然后,您可以使用 StaticResource 引用它。在 Google 上查找“WPF 样式” - 那里有很多很棒的文章。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2012-11-07
    相关资源
    最近更新 更多