WPF TextBox 触发器清除文本

发布于 2024-08-31 06:11:08 字数 646 浏览 1 评论 0原文

我有许多 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} />

那么触发器不起作用(可能是因为它已绑定) 如何克服这个问题呢?

I have many TextBox controls and I'm trying to write a style that clears the Text property when the Control is disabled.
I don't want to have Event Handlers in code behind.

I wrote this:

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

The problem is that if the TextBox is defined like:

<TextBox Text={Binding Whatever} />

then the trigger does not work (probably because it's bound)
How to overcome this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白色秋天 2024-09-07 06:11:08

由于您在 TextBox 中显式设置文本,因此样式的触发器无法覆盖它。试试这个:

<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>

Because you're explicitly setting the Text in the TextBox, the style's trigger can't overwrite it. Try this:

<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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文