How to use DataTrigger from Microsoft.Expression.Interactions


Recently I was working using WPF and needed to implement one behavior – change element property whenever underlying bound object changes its property.

I thought that DataTrigger form WPF will suit my needs but it turned out that it won’t:

<Grid> <TextBlock x:Name="txt" Text="Hello"/> <Grid.Triggers> <DataTrigger Binding="{Binding ShouldChangeFont}" Value="True"> <Setter TargetName="txt" Property="TextBlock.FontSize" Value="12"/> </DataTrigger> </Grid.Triggers> </Grid>

In that case runtime throws exception saying: "Triggers collection members must be of type EventTrigger."

Fortunately I was able to use DataTrigger in combination with ChangePropertyAction from the assembly named Microsoft.Expression.Interactions:

<StackPanel x:Name="stackPanel"> <TextBlock x:Name="txt" Text="Hello"> <i:Interaction.Triggers> <ie:DataTrigger Binding="{Binding ShouldChangeFont}" Value="True"> <ie:ChangePropertyAction PropertyName="FontSize" Value="24" /> </ie:DataTrigger> <ie:DataTrigger Binding="{Binding ShouldChangeFont}" Value="False"> <ie:ChangePropertyAction PropertyName="FontSize" Value="12" /> </ie:DataTrigger> </i:Interaction.Triggers> </TextBlock> <Button Content="Click" Click="Button_Click"/> </StackPanel>

As you can see, I’m able to declaratively describe what property should be changed based on certain condition. Also you could add multiple actions which would be invoked by trigger:

<ie:DataTrigger Binding="{Binding ShouldChangeFont}" Value="False"> <ie:ChangePropertyAction PropertyName="FontSize" Value="12" /> <ie:CallMethodAction MethodName="DoSomething"/> </ie:DataTrigger>

In this case when property ShouldChangeFont changes its value to false, ChangePropertyAction followed by CallMethodAction will be invoked.

You can use other available actions placed in this namespace or create your own.

That’s it. Hope this will help you in case you have similar needs.