Search code examples
c#wpfinheritancemetadatacontenttemplate

C# WFP Find control in control template of a control with override DefaultStyleKeyProperty


I have downloaded an example solution that uses the OverrideMetadata method of DefaultStyleKeyProperty of a control that inherits from usercontrol but does not have an .xaml design file, and that is going to be base control for other subcontrols with similar or almost same layout. The code can be found here Example.

Now I am trying to access from the base class to a button located in its content template of the overriden style, with the name of "btnTest1", but I cannot find the way to do this.

I would like to know if there is a way of finding the control in the base class constructor, or in the subclass constructor (maybe after calling InitializeComponent), because I need to have access to it in code-behind later.

Thanks in advance.

David.


Solution

  • There is a style pattern for this.

    In your control.cs file you want to override OnApplyTemplate

    protected override void OnApplyTemplate(){
    
          Button yourButtonControl = GetTemplateChild("TheNameOfYourButton") as Button;
    
          base.OnApplyTemplate();
    }
    
    1. If you'd like to follow the Microsoft pattern then first you will want to name your control "PART_SomethingButton". This just means it's a template part.

    2. Then in your Control.cs class, add an attribute on the Control.

      • This tells anyone that overrides your default style that if they want your code to work, they need to have a Button on their template with the name PART_SomethingButton

    .

    [TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
    public class MyControl : Control
    
    1. Inside of your class, add a private Button control.
      • We will use this to access our button throughout the control

    .

    [TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
    public class MyControl : Control{
         private Button _partSomethingButton;
    }
    
    1. Then finally set your private button in your OnApplyTemplate.
      • This goes into the template and caches the button in our cs file so that we can manipulate it or capture events off of it.

    .

    [TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
    public class MyControl : Control{
         private Button _partSomethingButton;
    
        protected override void OnApplyTemplate(){    
              _partSomethingButton = GetTemplateChild("PART_SomethingButton") as Button;   
              base.OnApplyTemplate();
        }
    }