在上一篇中我们说的控件模板,是定义在当前xaml窗口的静态资源中的,而实际项目中,往往几个窗口需要共用同一控件模板,甚至整个app都可以应用当前此控件模板,所以我们可以在当前app资源字典中定义控件模板。
1.使用资源字典
1.1新建资源字典
右键项目,新建Resources文件夹,在文件夹内新建资源字典,其实资源字典也是xaml文件。
将上一篇中名为btnTemplate的控件模板内容拷贝到资源字典里
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1.Resources">
<ControlTemplate x:Key="btnTemplate" TargetType="{x:Type Button}">
<Border x:Name="border1" Background="Blue" TextBlock.Foreground="White" BorderThickness="3">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="border1" Property="Background" Value="Red"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<!--应用到项目下button的控件模板 -->
<!--<Style TargetType="{x:Type Button}">
<Setter Property="Control.Template" Value="{StaticResource btnTemplate}"></Setter>
</Style>-->
</ResourceDictionary>
1.2合并资源字典
我理解的应该就是将app中定义的资源字典引入到当前xaml页面下,这样当前页面才能使用系统的资源字典。
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/ButtonStyle.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
使用方法不变。
<StackPanel>
<Button Content="DateTemplate Button1" Template="{StaticResource btnTemplate}"></Button>
</StackPanel>