WPF ListBox简单滑动动画
引用 Behaviors 库
首先,我们要引用Behaviors的库才能使用行为来添加动画(已经引用过的可以忽略这一步):
点击菜单栏 工具 > NuGet 包管理器 > 管理解决方案的 NuGet 程序包
搜索 Behaviors 得到的第一个结果 Microsoft.Xaml.Behaviors.Wpf
并按照上图依次点击按钮安装 Behaviors 库。
ListBox 使用动画
重写ListBox的Style(Style名为AnimateListStyle)写到 App.xaml 的资源里
(记得引用Behaviors 库:xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
):
<Application x:Class="AnimateListBox.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AnimateListBox"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="AnimateListStyle" TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true">
<ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
<b:Interaction.Behaviors>
<b:FluidMoveBehavior Duration="0:0:0.5">
<b:FluidMoveBehavior.EaseY>
<QuinticEase EasingMode="EaseOut"/>
</b:FluidMoveBehavior.EaseY>
<b:FluidMoveBehavior.EaseX>
<QuinticEase EasingMode="EaseOut"/>
</b:FluidMoveBehavior.EaseX>
</b:FluidMoveBehavior>
</b:Interaction.Behaviors>
</ItemsPresenter>
</ScrollViewer>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
</Trigger>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
然后在ListBox里调用这个 Style 并把 ListBox的ScrollViewer.CanContentScroll设置为False:
<ListBox Style="{StaticResource AnimateListStyle}" ScrollViewer.CanContentScroll="False"/>
就可以使用带有动画效果的ListBox了: