闲来无事,学习了一下wpf的控件模板知识,下面是设置按钮的例子。
首先定义控件模板,代码如下:
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
<Border Name="border" BorderBrush="Orange" BorderThickness="2" CornerRadius="3" Background="Red" TextBlock.Foreground="White">
<ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}"></ContentPresenter>
</Border>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="Background.Color" To="Blue" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever">
</ColorAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="Background.Color" Duration="0:0:0.5">
</ColorAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
在项目中添加资源字典,名称为Dictionary1.xaml,然后将上述模板代码拷贝到资源字典中即可。
下面就是在项目中的App.xaml文件中引用资源字典,代码如下:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
这样以后,就可以界面设计中对按钮添加模板引用即可,代码如下:
<Button Margin="10" Padding="5" Template="{StaticResource buttonTemplate}" Height="30" Width="100" TextBlock.TextAlignment="Center" Click="button1_Click">
<Button.Content>确认</Button.Content>
</Button>
至此,一个按钮的控件模板的例子就好了,非常简单。