Change StackPanel background color with ColorAnimation
Well, I'm trying to change the background color of a StackPanel in a DataTemplate using a 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: "The property" Background "does not point to a DependencyObject in the path" (0). (1) "."
What?: D
source to share
Your code worked fine for me. I just made small changes.
<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}" />
source to share
For documentation purposes:
A bit tricky to use (Panel.Background).(SolidColorBrush.Color)
. The real problem is that ColorAnimation
it only works for the property Color
instead of Brush
. For me this is the trick:
Define the panel brush ...
<StackPanel Name="SensorPanel" MouseDown="SensorPanel_MouseDown">
<StackPanel.Background>
<SolidColorBrush Color="White" x:Name="PanelColor"/>
</StackPanel.Background>
</StackPanel>
... then animate the property Color
SolidColorBrush
:
<ColorAnimation
Storyboard.TargetName="PanelColor"
Storyboard.TargetProperty="Color"
To="LawnGreen" Duration="0:0:0.25" AutoReverse="True" RepeatBehavior="4">
source to share