我下载了一个示例解决方案,该解决方案使用继承自usercontrol但没有OverrideMetadata设计文件的控件的DefaultStyleKeyProperty的DefaultStyleKeyProperty方法,该方法将成为具有类似或几乎相同布局的其他子控件的基本控件。代码可以在这里找到,示例。
现在,我试图从基类访问overriden样式内容模板中的一个按钮,名为"btnTest1",但我找不到这样做的方法。
我想知道是否有一种方法可以在基类构造函数或子类构造函数中找到控件(可能在调用InitializeComponent之后),因为以后我需要在代码隐藏中访问它。
提前谢谢。
大卫。
发布于 2016-07-21 13:31:19
这有一个样式模式。
在您的control.cs文件中,您希望覆盖OnApplyTemplate
protected override void OnApplyTemplate(){
Button yourButtonControl = GetTemplateChild("TheNameOfYourButton") as Button;
base.OnApplyTemplate();
}PART_SomethingButton“。这只意味着它是一个模板部件。Control.cs类中,在控件上添加一个attribute。- 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
。
[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();
}
}https://stackoverflow.com/questions/38501804
复制相似问题