Changing StackPanel Background color with ColorAnimation

liranxs picture liranxs · Mar 17, 2012 · Viewed 13.8k times · Source

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

Answer

Phil picture Phil · Mar 17, 2012

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}" />