【问题标题】:Prevent original template being applied in inherited control防止在继承控件中应用原始模板
【发布时间】:2017-06-04 02:49:04
【问题描述】:

我在应用程序中遇到问题,我想从商业库 (scichart) 中包含的控件派生我自己的自定义控件。

我正在重写 OnApplyTemplate,如下面的代码所示,但在调用 GetAndAssertTemplateChild 时遇到了一个问题(库中的一个函数与 GetTemplateChild 几乎相同,但如果结果为等于null)在模板中找不到该部分。

在调查此问题时,我发现 OnApplyTemplate 被多次调用,它首先使用继承自的控件模板调用,然后使用新控件的模板调用。有什么办法可以避免这种情况并且永远不要应用基类模板。

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

【问题讨论】:

  • 我想你也许可以使用stackoverflow.com/questions/5411962/…。但是,这对我来说似乎很麻烦。为什么不直接使用GetTemplateChild(),检查null 结果,如果是null,则跳过该方法的其余部分?如果您自己的模板中缺少该部分,那将是非常明显的。如果您真的很担心,您可以随时在其他地方验证您的自定义模板。

标签: c# wpf inheritance styles


【解决方案1】:

有什么办法可以避免这种情况,并且永远不要应用基类模板

如果你只想调用派生类的'OnApplyTemplate()方法,你应该避免在被覆盖的方法中调用基类'的方法:

public override void OnApplyTemplate()
{
    //DON't CALL THIS ONE: base.OnApplyTemplate();

    AnnotationRoot = GetAndAssertTemplateChild<Grid>("PART_LineAnnotationRoot");
    _line = GetAndAssertTemplateChild<Line>("PART_Line");
    _ghostLine = GetAndAssertTemplateChild<Line>("PART_GhostLine");
    _label = GetAndAssertTemplateChild<TextBlock>("PART_Label");
}

如果你想从头开始提供你自己的默认自定义ControlTemplate,你应该在你的控件类中定义一个静态构造函数:

static YourControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(YourControl),
        new FrameworkPropertyMetadata(typeof(YourControl)));
}

...并在名为“generic.xaml”的ResourceDictionary 中定义默认模板,该模板位于定义控件类的项目根文件夹中名为“Themes”的文件夹中。

【讨论】:

  • 我已经尝试过覆盖样式的方法,效果是一样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 1970-01-01
相关资源
最近更新 更多