【问题标题】:C# WFP Find control in control template of a control with override DefaultStyleKeyPropertyC# WPF 在具有覆盖 DefaultStyleKeyProperty 的控件的控件模板中查找控件
【发布时间】:2016-11-24 21:40:08
【问题描述】:

我已经下载了一个示例解决方案,该解决方案使用从 usercontrol 继承但没有 .xaml 设计文件的控件的 DefaultStyleKeyProperty 的 OverrideMetadata 方法,这将成为其他具有相似或几乎相同布局的子控件的基本控件. 代码可以在这里找到Example

现在我试图从基类访问位于其内容模板中的被覆盖样式的按钮,名称为“btnTest1”,但我找不到执行此操作的方法。

我想知道是否有办法在基类构造函数或子类构造函数中找到控件(可能在调用 InitializeComponent 之后),因为我需要稍后在代码隐藏中访问它。

提前致谢。

大卫。

【问题讨论】:

    标签: c# wpf inheritance metadata contenttemplate


    【解决方案1】:

    对此有一个样式模式。

    在您的 control.cs 文件中,您要覆盖 OnApplyTemplate

    protected override void OnApplyTemplate(){
    
          Button yourButtonControl = GetTemplateChild("TheNameOfYourButton") as Button;
    
          base.OnApplyTemplate();
    }
    
    1. 如果您想遵循 Microsoft 模式,那么首先您需要将控件命名为“PART_SomethingButton”。这只是意味着它是一个模板部分。

    2. 然后在您的Control.cs 类中,在控件上添加attribute

      • 这告诉任何覆盖您的默认样式的人,如果他们希望您的代码正常工作,他们需要在其模板上使用名称为 PART_SomethingButton 的Button

    .

    [TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
    public class MyControl : Control
    
    1. 在您的类中,添加一个私有 Button 控件。
      • 我们将使用它在整个控件中访问我们的按钮

    .

    [TemplatePart(Name = "PART_SomethingButton", Type = typeof(Button))]
    public class MyControl : Control{
         private Button _partSomethingButton;
    }
    
    1. 然后最后在 OnApplyTemplate 中设置您的私人按钮。
      • 这会进入模板并将按钮缓存在我们的 cs 文件中,以便我们可以对其进行操作或从中捕获事件。

    .

    [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();
        }
    }
    

    【讨论】:

    • 非常感谢。我通过附加到 Loaded 事件找到了一个解决方案,但我认为覆盖 OnApplyTemplate 方法是更好的解决方案。
    • @YakumoFujii 我发帖的方式是专业的方式
    猜你喜欢
    • 2011-12-26
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多