我有一个带有模板化 listboxitem 的列表框,它绑定到一个对象。listboxitem 控件之一是图像,它的源也绑定到 datacontext 内的属性,因此 Image 控件内的图片根据该属性而有所不同。我想为图像设置动画,但只有一个特定的(当绑定的属性值只是某个特定值时)。我想还有其他方法可以做到这一点,也许使用后面的代码。但我真的很想在 xaml 代码中使用它,所以我想在 DataTrigger 中使用动画,这对我来说很有意义,因为动画的开始/结束取决于 DataContext:
<DataTrigger Binding="{Binding Path=Value.SomeProperty}"
Value="SomePropertyValue">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard TargetName="SomePropertyIcon">
<StaticResource ResourceKey="SomePropertyValueAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard TargetName="SomePropertyIcon">
<StaticResource ResourceKey="StopSomePropertyValueAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
但我不能让它以任何方式工作。我试图将该代码放在 listBox 的样式中,然后将该样式应用于图像,它没有用,我还尝试将其放在 listBox.ItemTamplate 和其他地方,但没有任何帮助。这是代码。也许它可以帮助理解(我在这里只粘贴了相关代码):
<UserControl ...>
<UserControl.Resources>
<local:SomePropertyToImageConverter x:Key="somePropertyToImageConverter"/>
<DoubleAnimation x:Key="SomePropertyValueAnimation" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="45" Duration="0:0:2" RepeatBehavior="Forever"/>
<DoubleAnimation x:Key="StopSomePropertyValueAnimation" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="0" Duration="0:0:2"/>
</UserControl.Resources>
<Grid>
<ListBox Name="myListBox"
ItemsSource="{Binding Path=myDataContext}" IsEnabled="True" Focusable="True" SelectionMode="Extended">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Width="20" Height="20" Name="SomePropertyIcon"
Source="{Binding Path=Value.SomeProperty, Converter={StaticResource somePropertyToImageConverter}}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Value.SomeProperty}"
Value="SomePropertyValue">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard TargetName="SomePropertyIcon">
<StaticResource ResourceKey="SomePropertyValueAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard TargetName="SomePropertyIcon">
<StaticResource ResourceKey="StopSomePropertyValueAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Value.SomeProperty}"
Value="SomePropertyValue">
<Setter Property="Background" Value="Bisque"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>