如何继承控件模板 [英] How to Inherit a Control Template

查看:91
本文介绍了如何继承控件模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个WPF项目中工作,在该项目中,我为某些特殊操作重写了CheckBox控件.可以正常工作.

I working on a WPF project where I've over-ridden the CheckBox control for some special operations. That is working correctly.

我的问题是从主题(来自Codeplex的shnyred.xaml)应用的ControlTemplate未被应用于我的重写控件.有没有办法继承CheckBox ControlTemplate供我的新控件使用?

My problem is that the ControlTemplate that was applied from the theme (shinyred.xaml from codeplex), is not applied to my over-ridden control. Is there a way to inherit the CheckBox ControlTemplate for use by my new control?

我能找到的所有示例都集中在继承CheckBox的样式上,但是与ControlTemplate无关.

All the samples the I can find are focused on inheriting the style for the CheckBox, but nothing about the ControlTemplate.

推荐答案

否,正如您所说,可以使用BasedOn属性继承"样式,但是不能直接继承"模板.但这是可以理解的,模板继承的语义是什么?派生的模板将如何以某种方式在基本模板中添加或更改元素?

No, as you said it is possible to 'inherit' a style by using the BasedOn property, but it's not possible to directly 'inherit' a template. This is understandable though, what would be the semantics of template inheritance? How would the derived template be able to somehow add or change elements in the base template?

使用样式完全有可能,因为您可以简单地添加SettersTriggers等.可以想到的是,模板继承唯一可以做到的就是将Triggers添加到基本模板中.但是,在这种情况下,您必须对基础模板中的元素名称有深入的了解,并且基础模板中的元素名称更改可能会破坏您的派生名称.更不用说可读性的问题了,您在派生模板中引用一个名称,该名称完全在其他位置定义.

With styles it's entirely possible, since you can simply add Setters, Triggers, etc. The only thing that would conceivably be possible with template inheritance is adding Triggers to the base template. However, in that case you'd have to have intimate knowledge of the element names in the base template, and an element name change in the base template could break your derived one. Not to mention an issue with readability, where you refer to a name in your derived template, which is defined somewhere else entirely.

迟来的补充综上所述,有可能解决您的特定问题(尽管我现在怀疑这仍然是您的问题,甚至是一个问题).您只需为Template属性的设置器定义控件的样式,即可:

Belated Addition Having said all that, it is possible to resolve your particular problem (although I doubt by now it is still yours, or even a problem). You simply define a style for your control with a setter for the Template property thus:

<Style TargetType="<your type>">
    <Setter Property="Template" Value="{StaticResource <existing template resource name>}"/>
</Style>

这篇关于如何继承控件模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆