将上下文菜单从App.xaml附加到Setter值

本文关键字:Setter xaml 上下文 菜单 App | 更新日期: 2023-09-27 18:16:38

我在App.xaml中有一个ContextMenu,看起来像这样:

<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错误。什么好主意吗?

将上下文菜单从App.xaml附加到Setter值

正如评论中提到的,用DynamicResource -

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

参考这个参考- StaticResource vs DynamicResource

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

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文件中这样做,但是右键菜单项出现了,如果我将其更改为菜单项的标准填充,它们也会正确显示。

编辑:当我说标准人口时,我指的是这里解释的:

http://wpftutorial.net/ContextMenu.html