如何在代码后面的ListBox上禁用VisualState动画?我已经为ListBoxItem创建了Selected和Unselected VisualState故事板动画,但是当我的ListBox ItemsSource更改ListBox时,将执行Selected和Unselected动画(我认为所有项目都会自动被选中和取消选择一秒钟)。
编辑: 找到变通方法解决方案 - 如果您在项目源更改时获得选定和未选定动画,则可以使用它。看起来这样的自动选择更改甚至不会引发SelectionChanged事件。
public class ListBoxSelectedFoldersAnimationBehaviour : Behavior<ListBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += ListBoxOnSelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= ListBoxOnSelectionChanged;
}
private void ListBoxOnSelectionChanged(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
{
foreach (var item in selectionChangedEventArgs.AddedItems)
{
var listBoxItem = AssociatedObject.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
if (listBoxItem != null)
SetItemSelectedAnimation(listBoxItem);
}
foreach (var item in selectionChangedEventArgs.RemovedItems)
{
var listBoxItem = AssociatedObject.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
if (listBoxItem != null) // listboxitem can be null after removing item from ListBox.ItemsSource
SetItemUnselectedAnimation(listBoxItem);
}
}
private void SetItemSelectedAnimation(ListBoxItem item)
{ // sample opacity animation
var storyboard = new Storyboard();
var fadeOutAnimation = new DoubleAnimation()
{
EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut },
Duration = new Duration(TimeSpan.FromMilliseconds(200)),
From = 1.0,
To = 0.6
};
storyboard.Children.Add(fadeOutAnimation);
Storyboard.SetTarget(storyboard, item);
Storyboard.SetTargetProperty(storyboard, new PropertyPath(ListBoxItem.OpacityProperty));
storyboard.Begin();
}
private void SetItemUnselectedAnimation(ListBoxItem item)
{ // sample opacity animation
var storyboard = new Storyboard();
var fadeInAnimation = new DoubleAnimation()
{
EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseIn },
Duration = new Duration(TimeSpan.FromMilliseconds(200)),
From = 0.6,
To = 1.0
};
storyboard.Children.Add(fadeInAnimation);
Storyboard.SetTarget(storyboard, item);
Storyboard.SetTargetProperty(storyboard, new PropertyPath(ListBoxItem.OpacityProperty));
storyboard.Begin();
}
}
xaml:
<Page xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:classNamespace="clr-namespace:YourProjectName.NamespaceOfBehaviourClass">
...
<ListBox>
<i:Interaction.Behaviors>
<classNamespace:ListBoxSelectedFoldersAnimationBehaviour/>
</i:Interaction.Behaviors>
</ListBox>
我还没检查它是否泄漏内存(因为我没有停止故事板)所以记住这一点。