Reputation: 67
Well, I'm trying to change the Background color of a StackPanel in a DataTemplate using ColorAnimation:
<DataTemplate DataType="{x:Type logic:Sensor}">
<StackPanel Name="SensorPanel" MouseDown="SensorPanel_MouseDown">
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="0">
<!--<Setter TargetName="SensorPanel" Property="Background" Value="LawnGreen" />-->
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetName="SensorPanel"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="LawnGreen" Duration="0:0:0.25" AutoReverse="True" RepeatBehavior="4">
</ColorAnimation>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
No Compile-Time Errors. But when I run this an InvalidOperationException is thrown: "'Background' property does not point to a DependencyObject in path '(0).(1)'."
What? :D
Upvotes: 4
Views: 14155
Reputation: 7260
For documentation purposes:
It is a little hard to use (Panel.Background).(SolidColorBrush.Color)
. The real problem is that ColorAnimation
only works for the Color
property, instead of Brush
. For me this is the trick:
Define your panel brush...
<StackPanel Name="SensorPanel" MouseDown="SensorPanel_MouseDown">
<StackPanel.Background>
<SolidColorBrush Color="White" x:Name="PanelColor"/>
</StackPanel.Background>
</StackPanel>
...then animate the Color
property of SolidColorBrush
instead:
<ColorAnimation
Storyboard.TargetName="PanelColor"
Storyboard.TargetProperty="Color"
To="LawnGreen" Duration="0:0:0.25" AutoReverse="True" RepeatBehavior="4">
Upvotes: 12
Reputation: 43011
Your code worked perfectly for me. I just made minor modifications.
<DataTemplate DataType="{x:Type Model:Sensor}">
<StackPanel Name="SensorPanel" Background="LightBlue" Width="100" Margin="5">
<TextBlock Text="{Binding Name}"/>
<ToggleButton Margin="2" IsChecked="{Binding IsChecked}" Content="Set status=0" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="0">
<!--<Setter TargetName="SensorPanel" Property="Background" Value="LawnGreen" />-->
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetName="SensorPanel"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="LawnGreen" Duration="0:0:0.25" AutoReverse="True" RepeatBehavior="4">
</ColorAnimation>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<ListBox ItemsSource="{Binding Sensors}" />
Upvotes: 18