Saturday, August 2, 2014

MultiDataTrigger in WPF: an example

Here is the XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style x:Key="pricestyle" TargetType="TextBox">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding AllowCheck}" Value="True"/>
<Condition Binding="{Binding Action}" Value="SELL"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Visibility" Value="Visible"/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel Margin="20" HorizontalAlignment="Left">
<Label Content="Action" Margin="0,3,0,0"></Label>
<ComboBox Width="100" ItemsSource="{Binding Actions}" SelectedItem="{Binding Action, UpdateSourceTrigger=PropertyChanged}"></ComboBox>
<Label Content="Price" Margin="0,3,0,0"></Label>
<TextBox Width="100" Margin="0,3,0,0" Style="{StaticResource ResourceKey=pricestyle}"></TextBox>
<CheckBox x:Name="dd" Content="Allow" IsChecked="{Binding AllowCheck, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</StackPanel>
</Grid>
</Window>

On acceptable values defined in the trigger (highlighted in blue colour), on selection of Allow checkbox and SELL from action combo box, the trigger gets fired and the price textbox gets visible.


One important thing to note here (which may get missed out). Note the text in red colour. It's important to set a default state of the property for which you want the trigger to be applied on (in our example, its Visibility property of the textbox)

No comments :