wpf 帮我设计一个好看的expander样式,带有过度动画效果
时间: 2024-11-05 19:27:47 浏览: 12
在WPF中创建一个有吸引力的Expander样式并带有过渡动画效果,你可以自定义Expander的模板,并利用`DataTemplate`, `ControlTemplate`以及`Storyboard`来实现。下面是一个基本的设计步骤:
首先,在XAML中设置资源键,例如在App.xaml文件中:
```xml
<Application x:Class="YourAppName.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<Style TargetType="{x:Type Expander}">
<Setter Property="Template" Value="{StaticResource ExpanderStyle}"/>
</Style>
</Resources>
</Application>
```
然后,创建一个名为`ExpanderStyle`的`ControlTemplate`:
```xml
<Style x:Key="ExpanderStyle" TargetType="Expander">
<Setter Property="BorderBrush" Value="#FFAAB4B8"/>
<Setter Property="Background" Value="#F0F2F5"/>
<!-- 过渡动画部分 -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- 显示部分 -->
<ContentPresenter Grid.Column="1"
ContentSource="Header"
RecognizesAccessKey="True"
SnapsToDevicePixels="True"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="{TemplateBinding Padding}"
/>
<!-- 菊花按钮 -->
<ToggleButton x:Name="PART_Button"
Focusable="False"
Style="{DynamicResource ToggleButtonStyle}"
Grid.Column="0"
ContentTemplate="{StaticResource ExpandIconTemplate}"
IsChecked="{Binding IsExpanded, Mode=TwoWay}"
Template="{StaticResource ToggleButtonTemplate}"
Command="{TemplateBinding ExpandCommand}"
/>
</Grid>
<!-- 动画 storyboard -->
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded"
Value="True">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Button"
Storyboard.TargetProperty="(UIElement.Opacity)"
From="1.0" To="0.0"
Duration="0:0:0.3"
FillBehavior="Stop"
/>
</Storyboard>
</Trigger>
<Trigger Property="IsExpanded"
Value="False">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="PART_Button"
Storyboard.TargetProperty="(UIElement.Opacity)"
From="0.0" To="1.0"
Duration="0:0:0.3"
FillBehavior="Stop"
/>
</Storyboard>
</Trigger>
</ControlTemplate.Triggers>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
这里我们假设你已经有了`ExpandIconTemplate`和`ToggleButtonTemplate`作为内置图标模板和按钮样式。记得将这两个模板添加到你的资源集中。
最后,你可以在需要的地方使用这个样式:
```xml
<Expander Style="{StaticResource ExpanderStyle}" .../>
```
阅读全文