程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 《Programming WPF》翻譯 第9章 5.默認可視化

《Programming WPF》翻譯 第9章 5.默認可視化

編輯:關於.NET

雖然為控件提供一個自定義外觀的能力是有用的,開發者應該能夠使用一個控件而不用必須提供自定 義可視化。這個控件應該正好工作,當以它最直接的方式使用時。這意味著控件應該提供一組默認的值。

這些默認的可視化存儲在組件的二進制資源中,使用的源文件為theme"generic.xaml。如果你在 Visual Studio 2005中創建了一個WPF 控件庫的工程,這將自動添加這個文件到你的工程中,並且設置它 的Build Action為作為資源內嵌。(參見第6章獲取更多關於如何在組件中編譯xaml資源的信息)

在theme"generic.xaml文件中,定義一個樣式,攜有TargetType指定你的控件。這個樣式應該通過一 個ControlTemplate標簽設置Template屬性,為你的控件定義了默認可視化,正如示例9-17顯示的。參見 第5章獲取更多關於如何定義一個提供了模板的樣式的信息。

示例9-17

<?Mapping XmlNamespace="Local" ClrNamespace="CustomControlLib" ?>
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
    xmlns:x="http://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>

為了確定你的控件獲取了默認的主體,你需要讓依賴屬性系統知道樣式所在。如果你不這麼做,你只 能為你選擇的基類獲得默認值。示例9-18顯示了如何這麼做。

示例9-18

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

注意到Visual Studio 2005為你自動生成這段代碼,當你添加一個新的自定義控件到你的控件庫的工 程中。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved