当控件的类型具有全局样式时,如何仅更改 WPF 中应用程序的一部分的控件样式?
我在 App.xaml 中设置了 Menu/ContextMenu/MenuItem 控件的样式,以便这些样式适用于我的所有应用程序。
像这样定义(例如使用 MenuItem):
<Style TargetType="{x:Type MenuItem}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<!-- more setters -->
</Style>
这很好用。
现在,在某个时候我有一个 RichTextBox,我希望它的 ContextMenu 和 MenuItems 有不同的样式。
所以我写道:
<RichTextBox>
<RichTextBox.ContextMenu>
<ContextMenu>
<MenuItem Command="Undo" Style="{StaticResource menuItem}">Toto</MenuItem>
<MenuItem Command="Redo"/>
<Separator/>
<MenuItem Command="Cut"/>
<MenuItem Command="Copy"/>
<MenuItem Command="Paste"/>
<MenuItem Command="SelectAll"/>
</ContextMenu>
</RichTextBox.ContextMenu>
<!-- and here the RichTextBox's conent -->
</RichTextBox>
现在我试图弄清楚我可以在哪里放置我的新样式...问题是:我无法弄清楚:无论在哪里以及如何添加它(RichTextBox 上的静态资源,或者在 ContextMenu 上,使用显式 Key 或仅使用 targetType),我无法摆脱我的“全局”风格。而本地的就被忽略了。
我该如何继续?
I have styled my Menu/ContextMenu/MenuItem controls in App.xaml so that those styles apply to all my app.
defined like this (e.g. with the MenuItem):
<Style TargetType="{x:Type MenuItem}">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<!-- more setters -->
</Style>
this is working great.
now, at some point I have a RichTextBox, and I would like its ContextMenu and MenuItems to have a different style.
So I wrote:
<RichTextBox>
<RichTextBox.ContextMenu>
<ContextMenu>
<MenuItem Command="Undo" Style="{StaticResource menuItem}">Toto</MenuItem>
<MenuItem Command="Redo"/>
<Separator/>
<MenuItem Command="Cut"/>
<MenuItem Command="Copy"/>
<MenuItem Command="Paste"/>
<MenuItem Command="SelectAll"/>
</ContextMenu>
</RichTextBox.ContextMenu>
<!-- and here the RichTextBox's conent -->
</RichTextBox>
and now I'm trying to figure out where I can put my new style... Problem is: I can't figure it out: no matter where and How I add it (static ressource on the RichTextBox, or on The ContextMenu, with an explicit Key or just a targetType), I cannot get rid of my "Global" style. And the local one is just ignored.
how can I proceed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
Try:
最后,我选择了 ContextMenu 的资源,这甚至为我节省了每个菜单项中的“Style=...”。
我想我从一开始就有它,但不知何故忘记了 OverridesDefaultStyle = true 这似乎是问题所在。 (尽管根据我对 MS 文档的理解,它对我的情况应该没有任何影响......我必须尝试理解我在那里错过了什么)
In the end, I settled for the ContextMenu's resources, and this even saves me the "Style=..." in every menuItem.
I think I had it from the start, but somehow forgot the OverridesDefaultStyle = true which seemed to be the issue. (though from what I understood of the MS Documentation, it should not have made any difference in my case... I'll have to try and understand what I missed there)