Silverlight DataTrigger does not work when loading

I am trying to convert some of my WPF skills to Silverlight and have run into a slightly strange problem in a test gadget that I was working on. In WPF, I’m used to using DataTriggers in style to set management properties based on the properties of related data. I found that some assemblies related to Blend allow you to do something similar in Silverlight, and I came up with something like this that declares the following namespace:

xmlns:ia="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions" xmlns:iv="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" <DataTemplate x:Key="testItemTemplate"> <StackPanel Orientation="Horizontal"> <TextBox Text="{Binding Name, Mode=TwoWay}" x:Name="thing"/> <iv:Interaction.Triggers> <ia:DataTrigger Binding="{Binding Name}" Value="ReddenMe" Comparison="Equal"> <ia:ChangePropertyAction TargetName="thing" PropertyName="Foreground" Value="Red"> </ia:ChangePropertyAction> </ia:DataTrigger> </iv:Interaction.Triggers> </StackPanel> </DataTemplate> 

In this example, I have a data object that implements INotifyPropertyChanged and, as usual, raises the PropertyChanged event for the Name property. I get the expected behavior if I change the value of the text field and lose focus, but if the original value of the text field is set to ReddenMe (which for this contrived example I use as a trigger for text that should be red) the text will not be red. Does anyone know what is going on here? For DataTriggers in WPF, the trigger will immediately start for any data.

I understand that I could use the converter here, but I can think of situations where I would like to use triggers, and I am wondering if I can do anything to make this work.

+7
source share
1 answer

Here's the solution I found on Tom Peplow's blog: inherit from a DataTrigger and force the trigger to evaluate the condition when its related item is loaded.

Here you can encode it:

 public class DataTriggerEvaluateOnLoad : Microsoft.Expression.Interactivity.Core.DataTrigger { protected override void OnAttached() { base.OnAttached(); var element = AssociatedObject as FrameworkElement; if (element != null) { element.Loaded += OnElementLoaded; } } protected override void OnDetaching() { base.OnDetaching(); var element = AssociatedObject as FrameworkElement; if (element != null) { element.Loaded -= OnElementLoaded; } } private void OnElementLoaded(object sender, RoutedEventArgs e) { EvaluateBindingChange(null); } } 
+11
source

All Articles