開發者應該能直接使用控制項,而不必非得提供自訂樣式。控制項必須「開箱即用」,提供一組合理的預設外觀。
Themes/generic.xaml。Style,TargetType 指向你的控制項型別,並透過 Setter 設定 Template 屬性為 ControlTemplate。<?Mapping XmlNamespace="Local" ClrNamespace="CustomControlLib" ?>
<ResourceDictionary
xmlns="https://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="https://schemas.microsoft.com/winfx/xaml/2005"
xmlns:local="Local"
>
<Style TargetType="{x:Type local:MyCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
若不這麼做,控制項只會取得基底類別的預設樣式。必須在靜態建構式中註冊:
public class MyCustomControl : ContentControl {
static MyCustomControl() {
ThemeStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}
Visual Studio 2005 在加入新自訂控制項時會自動產生這段程式碼。
generic.xaml + ThemeStyleKeyProperty 覆寫。ControlTemplate 內使用 TemplateBinding 連結控制項屬性。ContentPresenter 作為內容佔位符,支援內容模型。