TemplatePart作用

TemplatePart(Name="PART_Decrease", Type=typeof(RepeatButton))

一直沒明白這是幹嘛用的,搜了一下,記載一下。


以Button的定義爲例:

namespace System.Windows.Controls
{
    // Summary:
    //     Represents a button control, which reacts to the Click event.
    [TemplatePart(Name = "Normal State", Type = typeof(Storyboard))]
    [TemplatePart(Name = "MouseOver State", Type = typeof(Storyboard))]
    [TemplatePart(Name = "RootElement", Type = typeof(FrameworkElement))]
    [TemplatePart(Name = "Pressed State", Type = typeof(Storyboard))]
    [TemplatePart(Name = "FocusVisualElement", Type = typeof(UIElement))]
    [TemplatePart(Name = "Disabled State", Type = typeof(Storyboard))]
    public class Button : ButtonBase
    {
        // Summary:
        //     Initializes a new instance of the Button class.
        public Button();
        // Summary:
        //     Apply a template to the Button.
        protected override void OnApplyTemplate();
        //
        // Summary:
        //     Called when the IsEnabled property changes.
        //
        // Parameters:
        //   isEnabled:
        //     New value of the IsEnabled property.
        protected override void OnIsEnabledChanged(bool isEnabled);
    }
}

 [TemplatePart(Name = "Normal State", Type = typeof(Storyboard))] 這種東東是做什麼用的 , 其實這是一種契約 , 是一種推薦的控件設計模式(只是推薦) , 意思是告訴要來寫ControlTemplate的用戶 , 你的ControlTemplate中需要有一個x:Name爲“Normal State” , 類型爲Storyboard , 當然這個類型可以是繼承來的, 爲什麼一定要包含這些契約規定的元素 , 因爲邏輯部分對這些東西進行了引用,它們將對控件的默認行爲起着關鍵作用, 可以理解爲這個控件的最基本元素 , 是實現默認行爲的最小集合, 自然,你的ControlTemplate中如果沒有包含契約中的內容 , 則相應的邏輯將無法實現。


所以說白了,就是提示用的.....這麼寫比較規範。


發佈了40 篇原創文章 · 獲贊 5 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章