将App.xaml中的上下文菜单附加到Setter Value

时间:2013-06-01 07:27:07

标签: c# wpf contextmenu

ContextMenu中的App.xaml看起来像这样:

<ContextMenu x:Key="TreeContextMenuTest" ItemsSource="{Binding ContextMenu}">....

然后我有一个ListView,其项目在Themes/Generic.xaml中设置了样式。它看起来像这样(我删除了不相关的的东西。风格应用得当,我的问题只是关于如何附加上下文菜单)

<Style TargetType='{x:Type ListViewItem}'>
    <Setter Property="ContextMenu" Value="{StaticResource TreeContextMenuTest}" />
</Style>

但是,我确实遇到DependencyProperty.UnsetValue is not a valid value for property ContextMenu错误。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

正如评论中提到的,而不是StaticResource使用DynamicResource -

<Setter Property="ContextMenu" Value="{DynamicResource TreeContextMenuTest}" />

请参阅此参考 - StaticResource vs DynamicResource

答案 1 :(得分:0)

我已经测试了你的解决方案,它似乎是有序的:

MainWindow.xaml:

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources>
        <Style TargetType='{x:Type ListViewItem}'>
            <Setter Property="ContextMenu" Value="{StaticResource TreeContextMenuTest}" />
        </Style>
    </Grid.Resources>
    <ListView>
        <ListViewItem>aaa</ListViewItem>
        <ListViewItem>bbb</ListViewItem>
        <ListViewItem>ccc</ListViewItem>
    </ListView>
</Grid>

的App.xaml:

<Application x:Class="WpfApplication3.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ContextMenu x:Key="TreeContextMenuTest" ItemsSource="{Binding ContextMenu}"/>

</Application.Resources>

App.xaml.cs:

public partial class App : Application
{
    public ObservableCollection<MenuItem> ContextMenu { get; set; }

    public App()
    {
        ContextMenu = new ObservableCollection<MenuItem>();
        var mi = new MenuItem {Name = "Test"};
        ContextMenu.Add(mi);
    }
}

我不知道您用来填充上下文菜单项的方式,我建议不要再进行绑定,在xaml文件中执行,但是右键菜单项出现了,如果我将其更改为标准menuItems的数量,他们也出现得恰到好处。

编辑: 当说标准人口时,我的意思如下:

http://wpftutorial.net/ContextMenu.html