首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF 自訂控制項的預設視覺化:generic.xaml 與主題樣式機制

     編輯:關於.NET

為什麼需要預設視覺化?

開發者應該能直接使用控制項,而不必非得提供自訂樣式。控制項必須「開箱即用」,提供一組合理的預設外觀。

generic.xaml:預設樣式的儲存地

  • 位於專案的 Themes/generic.xaml。
  • 在 Visual Studio 2005 建立 WPF 控制項庫專案時會自動加入,並設定 Build Action 為 Resource(內嵌資源)。
  • 裡面定義一個 Style,TargetType 指向你的控制項型別,並透過 Setter 設定 Template 屬性為 ControlTemplate。

範例:MyCustomControl 的預設模板

<?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>

啟用主題樣式:覆寫 ThemeStyleKeyProperty

若不這麼做,控制項只會取得基底類別的預設樣式。必須在靜態建構式中註冊:

public class MyCustomControl : ContentControl {
    static MyCustomControl() {
        ThemeStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl),
            new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }
}

Visual Studio 2005 在加入新自訂控制項時會自動產生這段程式碼。

關鍵重點

  • 預設視覺化 = generic.xaml + ThemeStyleKeyProperty 覆寫。
  • ControlTemplate 內使用 TemplateBinding 連結控制項屬性。
  • ContentPresenter 作為內容佔位符,支援內容模型。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved