How can I provide multiple conditions for data trigger in WPF?
In the previous chapter, we worked with triggers to get dynamic styles. So far they have all been based on a single property, but WPF also supports multi triggers, which can monitor two or more property conditions and only trigger once all of them are satisfied.
Basically, there are 3 types of triggers, they are: Property Trigger. Data Trigger. Event Trigger.
A DataTrigger allows you to set property values when the property value of the data object matches a specified Value. For example, if you are displaying a list of Employee objects, you may want the foreground color to be different based on each Employee's current attendance.
Use MultiDataTrigger type
<Style TargetType="ListBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Path=State}" Value="WA"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Path=Name}" Value="Portland" /> <Condition Binding="{Binding Path=State}" Value="OR" /> </MultiDataTrigger.Conditions> <Setter Property="Background" Value="Cyan" /> </MultiDataTrigger> </Style.Triggers> </Style>
@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)
but if you have values other than boolean try using type converters:
<MultiDataTrigger.Conditions> <Condition Value="True"> <Condition.Binding> <MultiBinding Converter="{StaticResource conditionConverter}"> <Binding Path="Name" /> <Binding Path="State" /> </MultiBinding> </Condition.Binding> <Setter Property="Background" Value="Cyan" /> </Condition> </MultiDataTrigger.Conditions>
you can use the values in Convert method any way you like to produce a condition which suits you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With