2017-06-04 37 views
0

我在我想从包含在商业库(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"); 
} 
+0

我想你可能能够使用https://stackoverflow.com/questions/5411962/wpf-styling-a-generic-base-control。但是,对我来说这似乎很麻烦。为什么不使用'GetTemplateChild()',检查一个'null'结果,并且如果它为空,则跳过该方法的其余部分?如果零件在您自己的模板中丢失,这将非常明显。如果你真的担心它,你可以随时在其他地方验证你的自定义模板。 –

回答

0

有什么办法避免这一点,并不会应用于基类模板

如果你只是想调用派生类的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,你建议立即进行删除D IN控件类中定义一个静态构造函数:

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

...在位于在项目的根文件夹名为“主题”文件夹中ResourceDictionary叫“generic.xaml”定义默认模板控制类被定义。

+0

我已经尝试过重写风格的方法,效果也一样。 – Hugoagogo