这是我的代码:
<DrawingBrush Viewport="0,0,16,16" ViewportUnits="Absolute" Stretch="None" TileMode="Tile" x:Key="dbCheckerBoard">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<GeometryGroup>
<RectangleGeometry Rect="0,0,8,8"/>
<RectangleGeometry Rect="8,8,8,8"/>
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
<Style x:Key="ScrollingCheckerBoardBackground" TargetType="Control">
<Setter Property="Background" Value="{StaticResource dbCheckerBoard}" />
<Style.Triggers>
<EventTrigger RoutedEvent="Control.Loaded">
<BeginStoryboard>
<Storyboard>
<RectAnimation Storyboard.TargetProperty="Background.Viewport" From="0 0 16 16" To="16 16 16 16" Duration="0:0:1" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
如果我将ScrollingCheckerBoardBackground
样式应用于ListBox
文件中的.XAML
,那么一切正常,但我想在代码隐藏中应用该样式,当用户点击{ {1}}。它不起作用,因为未调用Button
。
有没有办法在没有任何触发器的情况下为ListBox设置动画?
答案 0 :(得分:3)
Is there a way to animate the ListBox without any triggers?
不,要启动动画,您需要一个特定的动作或事件。
在这种情况下,如果在运行动画时ListBox的Tag为DataTrigger
,请尝试使用ShowAnimation
:
<Style x:Key="ScrollingCheckerBoardBackground" TargetType="Control">
<Setter Property="Background" Value="{StaticResource dbCheckerBoard}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Tag, RelativeSource={RelativeSource Mode=Self}}" Value="ShowAnimation">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<RectAnimation Storyboard.TargetProperty="Background.Viewport" From="0 0 16 16" To="16 16 16 16" Duration="0:0:1" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
在代码隐藏中写下这个:
private void Button_Click(object sender, RoutedEventArgs e)
{
MyListBox.Tag = "ShowAnimation";
}
Edit
你也可以像这样在代码隐藏中启动Storyboard
:
XAML
<Window.Resources>
...
<Storyboard x:Key="MyStoryboard">
<RectAnimation Storyboard.TargetProperty="Background.Viewport" From="0 0 16 16" To="16 16 16 16" Duration="0:0:1" RepeatBehavior="Forever" />
</Storyboard>
<Style x:Key="ScrollingCheckerBoardBackground" TargetType="Control">
<Setter Property="Background" Value="{StaticResource dbCheckerBoard}" />
</Style>
</Window.Resources>
<Grid>
<ListBox Name="MyListBox"
Style="{StaticResource ScrollingCheckerBoardBackground}"
Tag="Null"
Width="100"
Height="30" />
<Button VerticalAlignment="Bottom" Content="Click" Click="Button_Click" />
</Grid>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var story = (Storyboard)this.FindResource("MyStoryboard");
if (story != null)
story.Begin(MyListBox, true);
}
}