效果图:
鼠标移动到ListBox上就缓缓变大,鼠标移开就慢慢恢复原样
一.首先创建资源字典:ListBox.xaml
在资源字典中
1.创建画刷
<SolidColorBrush x:key="StandardBackgroundBrush" Color="#888"></SolidColorBrush>
<SolidColorBrush x:Key="StandardBorderBrush" Color="#FFF"></SolidColorBrush>
2.创建ListBox的Style
<!--Style样式,作用于ListBox-->
<Style TargetType="{x:Type ListBox}">
<Setter Property="Template"> <!--这个Setter作用于模板库, 模板在下面-->
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}"> <!--竟然是在Value下面定义模板-->
<Border
Name="Border"
Background="{StaticResource StandardBackgroundBrush}"
BorderBrush="{StaticResource StandardBorderBrush}"
BorderThickness="1"
CornerRadius="10"> <!--这个东西可以让ListBox的框变圆-->
<ScrollViewer Focusable="False">
<ItemsPresenter Margin="22"></ItemsPresenter> <!--这个设置Items和ListBox外边界距离-->
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
3.创建ListBoxItem的Style,包含触发器
<!--Style样式,作用于ListBox.Item-->
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Name="Border" BorderBrush="Green" BorderThickness="2" Padding="2" CornerRadius="5" SnapsToDevicePixels="True">
<ContentPresenter></ContentPresenter>
</Border>
<ControlTemplate.Triggers> <!--触发器-->
<EventTrigger RoutedEvent="ListBoxItem.MouseEnter"> <!--鼠标进入-->
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<!--动画,持续时间1秒-->
<DoubleAnimation Storyboard.TargetProperty="FontSize" To="20" Duration="0:0:1"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ListBoxItem.MouseLeave"> <!--鼠标离开-->
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard> <!--这里没有设置To它会自己缓动回去-->
<DoubleAnimation Storyboard.TargetProperty="FontSize" BeginTime="0:0:0.5" Duration="0:0:0.2"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
补充:如果给ControlTemplate设置了‘x:key’,Style使用这个模板的时候就不会自动作用于定义的全部控件了? 答:控件模板设置了键值,即使Style指定了作用类型,也不会自动使用,要自己调用这个模板。 像这里的如果ContorlTemplate在外面,需要在<Setter>中添加为Value的静态资源
二、在MainWindow窗口里,对ListBox添加资源字典
<ListBox.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ListBox.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ListBox.Resources>
补充:
可以在作用于BoxListItem的Style里面的触发器添加非动画触发器,实现鼠标放到上面和点击效果
<!--不是动画触发器,点击就立刻发生变化-->
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border1" Property="BorderBrush" Value="{StaticResource HoverBorderBrush}"></Setter> <!--这个就是Border的Name-->
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="border1" Property="Background" Value="{StaticResource SelectedBackgroundBrush}">
</Setter>
<Setter TargetName="border1" Property="TextBlock.Foreground" Value="{StaticResource SelectedForegroundBrush}"></Setter>
</Trigger>