WPF DataBound ListBox Animate on Add但不是Scroll

时间:2013-06-09 14:01:44

标签: wpf

我有一个绑定到ObservableCollection的WPF ListBox。当我向它添加项目时,我想要一些“引起注意”到“新到来”的动画。有许多使用DataTemplate触发器和FrameworkElment.Loaded事件执行此操作的示例。效果很好,看起来很酷。

但是,滚动列表时也会触发相同的动画。这是由于ListBox的虚拟化功能,它根据需要“加载”新项目。

有没有办法构造一个ListBox,以便它只在ObservableCollection更改时触发“已加载”动画,而不是在滚动时触发?

P.S。禁用虚拟化不是一种选择

1 个答案:

答案 0 :(得分:3)

要触发动画,我创建了附加的依赖项属性AddNewItem(Boolean):

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty AddNewItemProperty;

    public static void SetAddNewItem(DependencyObject DepObject, bool value)
    {
        DepObject.SetValue(AddNewItemProperty, value);
    }

    public static bool GetAddNewItem(DependencyObject DepObject)
    {
        return (bool)DepObject.GetValue(AddNewItemProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata(false);

        AddNewItemProperty = DependencyProperty.RegisterAttached("AddNewItem",
                                                            typeof(bool),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

然后创建我们的依赖属性的边框(警告添加新项):

<Border x:Name="WarningBorder" Style="{StaticResource HideBorderStyle}" local:MyDependencyClass.AddNewItem="False" Height="33" Background="#44515B" BorderThickness="0" Margin="65,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Opacity="0">
        <TextBlock x:Name="WarningText" FontFamily="./#Segoe UI" TextAlignment="Center" Margin="0,5,0,0" FontSize="18" Foreground="Gainsboro" Text="You add new item" />
</Border>

样式HideBorderStyle包含属性AddNewItem = True时触发的 DataTrigger 。 HideBorderStyle列表:

    <Style x:Key="HideBorderStyle" TargetType="{x:Type Border}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=WarningBorder, Path=(local:MyDependencyClass.AddNewItem), Mode=OneWay}" Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="Width" BeginTime="0:0:0" From="0.0" To="427.0" Duration="0:0:0.5" />
                            <DoubleAnimation Storyboard.TargetProperty="Opacity" BeginTime="0:0:0" From="0.0" To="1.0" Duration="0:0:1.0" />
                            <DoubleAnimation Storyboard.TargetProperty="Opacity" BeginTime="0:0:5" From="1.0" To="0.0" Duration="0:0:1.0" />
                            <DoubleAnimation Storyboard.TargetProperty="Width" BeginTime="0:0:5" From="427.0" To="0.0" Duration="0:0:1.0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>

假设我们有一个SampleListBox和AddButton:

 <Grid>
     <ListBox x:Name="SampleListBox" Width="400" Height="200" BorderThickness="1" BorderBrush="Black" DisplayMemberPath="Name" Background="AliceBlue" Loaded="SampleListBox_Loaded" />

     <Button Content="Add" Width="50" Height="30" VerticalAlignment="Bottom" Click="AddButton_Click" />
</Grid>

AddButton_Click列表:

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {            
        PersonListBox.Add(new Person()
        {
            Name = "NewItem",
        });

        SampleListBox.ItemsSource = PersonListBox;            
    }

在SampleListBox_Loaded中,我初始化SampleListBox的数据并分配一个处理程序 NotifyCollectionChangedEventHandler ,当集合发生变化时会调用它。 SampleListBox_Loaded事件列表:

private void SampleListBox_Loaded(object sender, RoutedEventArgs e)
{
    PersonListBox.Add(new Person()
    {
        Name = "Peter Orange",
        Age = 32,
        Sample = "Sample",
    });

    SampleListBox.ItemsSource = PersonListBox;
    PersonListBox.CollectionChanged += new NotifyCollectionChangedEventHandler(PersonListBox_CollectionChanged);
}

在PersonListBox_CollectionChanged中,为依赖项属性AddNewItem设置值 True 。 PersonListBox_CollectionChanged的列表:

    private void PersonListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            MyDependencyClass.SetAddNewItem(WarningBorder, true);             
        }
    }

现在,当项目添加到集合时会触发动画。如果添加另一个未触发的元素动画。所以她工作,你需要为未来的显示动画折叠值:

private void ResetButton_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetAddNewItem(WarningBorder, false);
}

在这种情况下,您需要决定何时重置动画的值。

修改

根据我之前的示例制作添加项目的动画。但是现在为 ListBoxItem 分配带 DataTrigger 的样式:

  <ListBox x:Name="SampleListBox" local:MyDependencyClass.AddNewItem="False" local:MyDependencyClass.InitCountOfList="0" Width="400" Height="200" BorderThickness="1" BorderBrush="Black" DisplayMemberPath="Name" Background="AliceBlue" Loaded="SampleListBox_Loaded">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Triggers>                        
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding ElementName=SampleListBox, Path=(local:MyDependencyClass.AddNewItem), Mode=OneWay}" Value="True" />
                            <Condition Binding="{Binding ElementName=SampleListBox, Converter={StaticResource BoolToInitItemsConverter}}" Value="True" />
                        </MultiDataTrigger.Conditions>

                        <MultiDataTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" BeginTime="0:0:0" From="0.0" To="1.0" Duration="0:0:1.0" />
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiDataTrigger.EnterActions>
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

为了正确的工作,动画(特别是在程序的开头)是根据另一个属性创建的 - InitCountOfList(Int):

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty AddNewItemProperty, InitCountOfListProperty;

    #region AddNewItem

    public static void SetAddNewItem(DependencyObject DepObject, bool value)
    {
        DepObject.SetValue(AddNewItemProperty, value);
    }

    public static bool GetAddNewItem(DependencyObject DepObject)
    {
        return (bool)DepObject.GetValue(AddNewItemProperty);
    }

    #endregion

    #region InitCountOfList

    public static void SetInitCountOfList(DependencyObject DepObject, int value)
    {
        DepObject.SetValue(InitCountOfListProperty, value);
    }

    public static int GetInitCountOfList(DependencyObject DepObject)
    {
        return (int)DepObject.GetValue(InitCountOfListProperty);
    }

    #endregion 

    #region Constructor of DependencyProperty

    static MyDependencyClass()
    {
        PropertyMetadata BoolPropertyMetadata = new PropertyMetadata(false);
        PropertyMetadata IntPropertyMetadata = new PropertyMetadata(0);

        AddNewItemProperty = DependencyProperty.RegisterAttached("AddNewItem",
                                                            typeof(bool),
                                                            typeof(MyDependencyClass),
                                                            BoolPropertyMetadata);

        InitCountOfListProperty = DependencyProperty.RegisterAttached("InitCountOfList",
                                                                 typeof(int),
                                                                 typeof(MyDependencyClass),
                                                                 IntPropertyMetadata);
    }

    #endregion
}

数据在Window_ContentRendered事件中初始化:

 private void Window_ContentRendered(object sender, EventArgs e)
 {
     PersonListBox.Add(new Person()
     {
         Name = "Peter Orange",                              
     });

     SampleListBox.ItemsSource = PersonListBox;

     // Set the initial number of collection
     MyDependencyClass.SetInitCountOfList(SampleListBox, SampleListBox.Items.Count);
 }

处理程序 NotifyCollectionChangedEventHandler 在SampleListBox_Loaded事件中分配:

private void SampleListBox_Loaded(object sender, RoutedEventArgs e)
{            
    PersonListBox.CollectionChanged += new NotifyCollectionChangedEventHandler(PersonListBox_CollectionChanged);
}

Handler和AddButton_Click保持不变:

private void PersonListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        MyDependencyClass.SetAddNewItem(SampleListBox, true);
    }
}

private void AddButton_Click(object sender, RoutedEventArgs e)
{            
    PersonListBox.Add(new Person()
    {
        Name = "NewItem",
    });
}

转换器 BoolToInitItemsConverter ,如果在启动期间没有添加元素,则返回true:

/// <summary>
/// Return true, if count of collection > initial
/// </summary>
public class BoolToInitItemsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ListBox MyListBox = value as ListBox;
        int InitCountOfList = MyDependencyClass.GetInitCountOfList(MyListBox);

        if (MyListBox.Items.Count > InitCountOfList)
        {
            // Added a new element
            return true;
        }

        // First run and we do not want
        // to run the animation
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue as object;
    }
}

现在动画作品仅适用于添加的项目。