TemplatePart作用

2798 ワード


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);
    }
}
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に契約の内容が含まれていなければ、相応の論理は実現できません.