C# ContextMenu出现问题,无法显示项目

C# ContextMenu出现问题,无法显示项目,c#,wpf,data-binding,contextmenu,C#,Wpf,Data Binding,Contextmenu,目标: 右键单击列表框并获得绑定的上下文菜单 public class MyViewModel { public List<string> ContextMenuItems{ get; set; } public ItemObject MyObject{ get; set; } } public class ItemObject{ public List<OtherObjects> SomeCollection{ get; set; } }

目标: 右键单击列表框并获得绑定的上下文菜单

public class MyViewModel
{

    public List<string> ContextMenuItems{ get; set; }
    public ItemObject MyObject{ get; set; }
}

public class ItemObject{
    public List<OtherObjects> SomeCollection{ get; set; }
}
公共类MyViewModel
{
公共列表ContextMenuItems{get;set;}
公共项目对象MyObject{get;set;}
}
公共类ItemObject{
公共列表集合{get;set;}
}
现在我的ListBox绑定到“SomeCollection”,但是我的ContextMenu应该访问ListBox绑定之外的绑定。我已经试过了,但根本无法让它工作,我的上下文菜单总是空的。知道为什么吗?这是在UserControl中,而不是窗口中,与此无关。我只是指出为什么我的AncestorType指向一个UserControl

<ListBox ItemsSource="{Binding SomeCollection}">
<ListBox.ContextMenu >
<ContextMenu DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" ItemsSource="{Binding ContextMenuItems}">
    <ContextMenu.ItemTemplate> 
        <DataTemplate>
            <MenuItem Header="{Binding}" Command="{Binding MyCommand}"/>
        </DataTemplate>
    </ContextMenu.ItemTemplate>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>

上下文菜单在WPF中绑定起来非常棘手。原因是它们存在于可视化树之外,而其余组件则存在于可视化树之外。(如果你仔细想想,这是有道理的,因为它们在自己的弹出窗口中)

正如您所发现的,由于它们位于不同的可视树中,所以能够按名称绑定之类的有用功能会导致绑定错误。“找不到源”表示它在可视化树中找不到命名元素

绕过它的一种方法是使用上下文菜单本身的“PlacementTarget”属性。这是指父控件,您可以在其中访问数据上下文,如下所示:

<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" ItemsSource="{Binding ContextMenuItems}">
在您的资源中,当您在访问正确的DataContext时遇到困难时,请创建代理对象:

<UserControl.Resources>
    <local:BindingProxy x:Key="Proxy" Data="{Binding}" />
</UserControl.Resources>

然后,您可以在xaml中的任何位置轻松访问它:

<ContextMenu ItemsSource="{Binding Data.ContextMenuItems, Source={StaticResource Proxy}}">


绑定错误是什么?(它出现在“输出”窗口中)。让上下文菜单正确绑定总是要花费我很多时间…看看绑定到ContextMenuItems的ItemsSource,这是一个字符串列表。标题绑定对我来说是正确的,并且绑定到一个元素,但是什么是MyCommand?我认为字符串中不存在该属性。@Joe System.Windows.Data错误:4:找不到引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.UserControl',AncestorLevel='1'的绑定源。BindingExpression:Path=DataContext.StandardLinksContextMenu;DataItem=null;目标元素是“ContextMenu”(名称=“”);目标属性是'ItemsSource'(类型'IEnumerable')。我甚至给我的UserControl起了一个名字“rootElement”,并试图通过:,找到它,但仍然说找不到Source。我刚刚创建并实现了它,无论如何,谢谢。很好的解决方案,非常感谢
<ContextMenu ItemsSource="{Binding Data.ContextMenuItems, Source={StaticResource Proxy}}">