Reputation: 218
I'm trying to setup a trigger so if two values match a color change happens, this is easy when the thing to match is static and can be placed right into xaml, but not when the thing to be compared is dynamic, such as a property. Basically is there anyway to bind the value of a trigger to a property?
Example - Error says value can not use a binding. This leads me to think that value has to be static.
<TextBlock Name="MyTextBlock" Text="{Binding someProp}">
<TextBlock.Resources>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MyTextBlock, Path=Text}" Value="{Binding someOtherProperty}">
Do some stuff here
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Resources>
</Textblock>
EDIT: Updated it to a data trigger, but the issue remains.
Upvotes: 4
Views: 5297
Reputation: 7918
For this purpose you may use DataTriggers
like shown in the example below (TextBlock
named txtBlock
color changes depends on the value "R" or "N"):
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=txtBlock,Path=Text}" Value="R">
<Setter Property="Background" Value="#f9f9f9" />
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=txtBlock,Path=Text}" Value="N">
<Setter Property="Background" Value="Yellow" />
<Setter Property="Foreground" Value="Black" />
</DataTrigger>
</Style.Triggers>
Solution works for any finite data set used in condition. For more complex condition (e.g. variable used in condition block, etc) you can implement the value converter and binding in code-behind like shown in the example: Binding in WPF DataTrigger value. Also, you may consider MultiDataTrigger
, or DataTrigger
with MultiBinding
(re: MultiDataTrigger vs DataTrigger with multibinding).
Hope this may help.
Upvotes: 4