适用于'MenuItem'类型的样式不能应用于'Separator'类型 [英] A style intended for type 'MenuItem' cannot be applied to type 'Separator'

查看:484
本文介绍了适用于'MenuItem'类型的样式不能应用于'Separator'类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ContextMenu的WPF窗口应用程序.

I'm working on WPF Window Application which uses ContextMenu.

我在XAML中的ContextMenu(在Window.Resources中):

My ContextMenu in XAML (in Window.Resources):

<ContextMenu x:Key="menuList" Placement="Bottom" >
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Header" Value="{Binding Name}"/>
            <EventSetter Event="Click" Handler="cm_RefreshChannelNotification"/>
            <Setter Property="IsChecked" Value="{Binding CFiltered}" />
            <Setter Property="IsCheckable" Value="True"/>
            <Setter Property="StaysOpenOnClick" Value="True"/>           
        </Style>
    </ContextMenu.ItemContainerStyle> 
</ContextMenu> 

当我尝试将分隔符添加到ContextMenu时,我收到错误消息:

When I try to add Separator to the ContextMenu I receive error:

System.InvalidOperationException未处理 Message =用于'MenuItem'类型的样式不能应用于'Separator'类型.

System.InvalidOperationException was unhandled Message="A style intended for type 'MenuItem' cannot be applied to type 'Separator'.

这样,我必须添加一个新的分隔符:

In this way I must add a new separator:

ContextMenu cm = this.FindResource("menuList") as ContextMenu;
Separator separator = new Separator();
separator.SnapsToDevicePixels = true;  
cm.Items.Add(separator);

我应该更改/添加ContextMenu定义以使其起作用吗?

What should I change/add in ContextMenu definition to make it work?

推荐答案

您可以将样式移动到ContextMenu.Resources,这会将其隐式应用于不会与Separators冲突的菜单项.

You can move the style to the ContextMenu.Resources, this applies it implicitly to the menu items which will not conflict with the Separators.

另一种选择是删除TargetType并限定属性,不应用的属性可能会被忽略.我自己从来没有做过:

An alternative may be to drop the TargetType and qualify the properties, non-applying properties might be ignored. Never did this myself though:

<Style>
    <Setter Property="MenuItem.Header" Value="{Binding Name}"/>

这篇关于适用于'MenuItem'类型的样式不能应用于'Separator'类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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