WPF中的用法DataTrigger [英] Usage DataTrigger in WPF
问题描述
我在XAML中定义了TextBox
控件,并且我想根据其IsReadOnly或IsEnabled属性将不同的背景色应用于TextBox
.我使用dataTriggers实际上在颜色之间进行切换,如下所示:
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.
上述方法是否有问题?
推荐答案
我认为您只需要在绑定中添加RelativeSource={RelativeSource Self}
:
I think you need just need to add RelativeSource={RelativeSource Self}
to your bindings:
<Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="True">
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
<DataTrigger Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="True"/>
<Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="True"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Green"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
但是仍然存在一个问题,我不相信您会看到红色背景,因为具有IsEnabled属性设置为False的TextBox在其控件模板中具有内置背景色,它将优先于样式触发器的触发器设置器.
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.
我认为您必须重新定义其控件模板才能在禁用TextBox时更改背景颜色.
I think you'd have to redefine its control template to change the background color when the TextBox is disabled.
这篇关于WPF中的用法DataTrigger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!