如何更改 ControlTemplate 的视觉状态而不替换它?
我想定义一个 ToggleButton
在选中时以红色前景显示(例如),而不是按下按钮的默认外观。
我看到视觉状态在 ToggleButton
的 ControlTemplate
中作为命名元素进行维护。
在不重新定义整个模板的情况下替换/删除/自定义视觉状态的最简单方法是什么?
I want to define a ToggleButton
that appears with red foreground (for example) when checked, rather than the default appearance of a pressed button.
I see that the visual states are maintained as named elements inside the ToggleButton
's ControlTemplate
.
What is the easiest way to replace/remove/customize a visual state WITHOUT redefining the entire template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我意识到这已经很晚了,但我刚刚遇到了同样的问题并自己找到了解决方案,所以希望这对某人有用。
将模板应用于控件后(第一个测量/显示周期后),您只需使用
VisualTreeHelper.GetChild (myToggleButton, 0)
即可访问实例化的模板及其子组件 - 这将返回实例化模板可视树的根对象,您可以从中添加/删除/修改其 Children 集合中的子对象。显然,您只是更改控件实例的视觉状态,而不是模板资源本身,因此从同一模板创建的新控件仍将具有原始的视觉外观。
我关于这个主题的相关问题在这里:如何在运行时在 Silverlight 3 中替换 ControlTemplate 部分?
I realise this is very late, but I just ran into the same issue and figured out the solution myself, so hopefully this will be useful to someone.
After the template has been applied to a control (after the first measure/display cycle), you can access the instantiated template and its child components simply by using
VisualTreeHelper.GetChild (myToggleButton, 0)
- this will return the root object of the instantiated template's visual tree, from which you can add/remove/modify the child objects in its Children collection.Obviously you're only changing the visual state of that instance of the control, not the template resource itself, so new controls created from the same template will still have the original visual appearance.
My realted question on this subject is here: How do I replace a ControlTemplate part at runtime, in Silverlight 3?
您是否尝试过创建自己的
ControlTemplate
并将BasedOn
参数设置为标准,然后仅更改您需要的内容?Have you tried creating your own
ControlTemplate
and set theBasedOn
parameter to standard and then only changed what you needed?