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.
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();
}
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.
Then in your Control.cs
class, add an attribute
on the Control.
Button
on their template with the name PART_SomethingButton.
[TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
public class MyControl : Control
.
[TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
public class MyControl : Control{
private Button _partSomethingButton;
}
.
[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();
}
}