首页 > 解决方案 > 使用行为动画 DataGridRow

问题描述

在某些情况下,我需要为一行设置动画。我有一个仅在某个属性更改时运行的 Behaivor。我遇到的问题是,当行为结束时,我失去了以前拥有的所有动画。在动画前后观察鼠标。另外,完成后,请观察我单击该行的时间。有什么解决办法吗?

.gif 在此处输入图像描述

public enum Events
{
    Changed
}

public class AnimateBehavior : Behavior<TextBlock>
{
    public Events Property { get; set; }

    private ColorAnimation ColorAnimation { get; set; }

    public Brush BackgroundBrush { get; set; }

    protected override void OnAttached()
    {
        ColorAnimation = new ColorAnimation
        {
            AutoReverse = true,
            To = Colors.LightBlue,
            From = Colors.Transparent,
            FillBehavior = FillBehavior.Stop,
            RepeatBehavior = new RepeatBehavior(3),
            Duration = new Duration(TimeSpan.FromMilliseconds(500))
        };

        AssociatedObject.DataContextChanged += OnDataContextChanged;
        WireEvents();
    }

    private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.OldValue is INotifyPropertyChanged oldData)
        {
            oldData.PropertyChanged -= OnPropertyChanged;
        }
        WireEvents();
    }

    private void WireEvents()
    {
        if (AssociatedObject.DataContext is INotifyPropertyChanged currentData)
        {
            currentData.PropertyChanged += OnPropertyChanged;
        }
    }

    private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (Property == Events.Changed)
        {
            var dataGridRow = AssociatedObject.TryFindParent<DataGridRow>();
            //ColorAnimation.Completed += (s, x) =>
            //{
            //    dataGridRow.Background = Brushes.Transparent;
            //};
            dataGridRow.Background =
                (SolidColorBrush) new BrushConverter().ConvertFromString(dataGridRow.Background.ToString());
            dataGridRow.Background?
                .BeginAnimation(SolidColorBrush.ColorProperty, ColorAnimation);
        }
    }

    protected override void OnDetaching()
    {
        if (AssociatedObject.DataContext is INotifyPropertyChanged currentData)
        {
            currentData.PropertyChanged -= OnPropertyChanged;
        }
    }
}

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding LastUpdated}">
            <Interactivity:Interaction.Behaviors>
                <customBehavior:AnimateBehavior Property="Changed" />
            </Interactivity:Interaction.Behaviors>
        </TextBlock>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

标签: c#wpfxamlmahapps.metro

解决方案


推荐阅读