将项目添加到列表框时动画 WPF 数据模板?

问题描述:

在我的项目中,我有一个绑定到 ObservableCollection 的 WPF 列表框.每次我向集合添加新项目时,相同的项目都会自动添加到列表框.为了显示列表框中的项目,我使用了 XAML 数据模板.

In my project I have a WPF Listbox bound to an ObservableCollection. Every time I add a new item to the Collection the same item is added to the Listbox automaticly. To display the items in the Listbox I use a XAML Datatemplate.

我想要做的是在将项目添加到集合/列表框时对其进行动画处理.这能做到吗?作为数据模板中的动画可能吗?我想我需要一个触发器来启动这个动画,但是当添加新项目/数据模板时会触发什么触发器?

What I want to do is animate an item once when it is added to the Collection/Listbox. Can this be done? As animation in the datatemplate maybe? I guess I need a trigger somehow to start this animate but what trigger is fired when a new item/datatemplate is added?

我认为 FrameworkElement.Loaded 路由事件的事件触发器可以工作.例如:

I think an event trigger for the FrameworkElement.Loaded routed event could work. For example:

<DataTemplate DataType="{x:Type l:Foo}">
    <Button x:Name="Button" Content="{Binding Path=Bar}">
        <Button.Background>
            <SolidColorBrush x:Name="ButtonBrush" Color="Tan" />
        </Button.Background>
    </Button>
    <DataTemplate.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded" SourceName="Button">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetName="ButtonBrush" Storyboard.TargetProperty="Color" To="Red" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </DataTemplate.Triggers>
</DataTemplate>