不管在SL或WPF中,在创建自定义控件时,我们有可能需要在Generic.xaml中定义多个控件的Style,定义的多了找起来就很麻烦,如果在单个文件里定义好,然后在Generic.xaml中包含(include)岂不是很好,Generic.xaml代码如下:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/WpfCustomControlLibrary1;component/CustomControl1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
CustomControl1.cs:
namespace WpfCustomControlLibrary1
{
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
CustomControl1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary1"
>
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<WrapPanel>
<Label Background="Yellow">昨天</Label>
<Label Background="Green">今天</Label>
<Label Background="Orange">明天</Label>
</WrapPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
依赖属性标识符字段: DefaultStyleKeyProperty
若要为继承自 Control 的控件提供默认的 Style,请将 DefaultStyleKey 属性设置为相同类型的 TargetType 属性。如果您没有设置 DefaultStyleKey,则将使用基类的默认样式。例如,如果称为 NewButton 的控件继承自 Button,要使用新的默认 Style,请将 DefaultStyleKey 设置为类型 NewButton。如果您没有设置 DefaultStyleKey,则会将 Style 用于 Button。