在 WPF 中使用 DataTrigger
我有一个在 XAML 中定义的 TextBox
控件,我想根据其 IsReadOnly 或 IsEnabled 属性将不同的背景颜色应用于 TextBox
。我使用 dataTriggers 实际上在颜色之间切换,如下所示:
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled}" Value="True">
<Setter Property="TextBox.Background" Value="Yellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsReadOnly}" Value="True">
<Setter Property="TextBox.Background" Value="Red"/>
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsReadOnly}" Value="True"/>
<Condition Binding="{Binding IsEnabled}" Value="True"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Green"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
并且 TextBox 的定义如下所示:
<TextBox Name="sourceTextBox" Margin="5,3,5,3" IsReadOnly="True" Style="{StaticResource TextBoxStyle}" />
但问题是,颜色没有正确应用。
上面的做法有问题吗?
I have a TextBox
control defined in XAML and I want to apply different background colors to the TextBox
based on its IsReadOnly or IsEnabled properties. I used dataTriggers to actually switch between the colors as shown below:
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled}" Value="True">
<Setter Property="TextBox.Background" Value="Yellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsReadOnly}" Value="True">
<Setter Property="TextBox.Background" Value="Red"/>
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsReadOnly}" Value="True"/>
<Condition Binding="{Binding IsEnabled}" Value="True"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Green"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
And the TextBox is defined as shown below:
<TextBox Name="sourceTextBox" Margin="5,3,5,3" IsReadOnly="True" Style="{StaticResource TextBoxStyle}" />
But the problem is, the colors are not being applied properly.
Is there any problem with the above approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你让事情变得不必要地复杂化
You are unecessarily complicating things
我认为您只需要添加
RelativeSource={RelativeSource Self}
到您的绑定中:但是仍然存在一个问题,我不相信您会看到红色背景,因为带有 IsEnabled 的 TextBox设置为 False 的属性在其控件模板中具有内置背景颜色,该背景颜色将优先于样式触发器的设置器。
我认为当 TextBox 被禁用时,您必须重新定义其控件模板才能更改背景颜色。
I think you need just need to add
RelativeSource={RelativeSource Self}
to your bindings:There is still one problem however, I don't believe you will ever see a Red background because a TextBox with its IsEnabled property set to False has a built in background color into its control template that will take priority over your style's trigger's setter.
I think you'd have to redefine its control template to change the background color when the TextBox is disabled.