我使用MVVM将视图绑定到树中的对象。我有一个实现在我的树中的项目一个基类和基类有一个ContextMenu属性:使用MVVM,ContextMenu ViewModel如何找到打开ContextMenu的ViewModel?
public IEnumerable<IMenuItem> ContextMenu
{
get
{
return m_ContextMenu;
}
protected set
{
if (m_ContextMenu != value)
{
m_ContextMenu = value;
NotifyPropertyChanged(m_ContextMenuArgs);
}
}
}
private IEnumerable<IMenuItem> m_ContextMenu = null;
static readonly PropertyChangedEventArgs m_ContextMenuArgs =
NotifyPropertyChangedHelper.CreateArgs<AbstractSolutionItem>(o => o.ContextMenu);
结合基类(和所有派生类)实现了结合到一个文本菜单的查看属性:
<ContextMenu x:Name="contextMenu" ItemsSource="{Binding Path=(local:AbstractSolutionItem.ContextMenu)}"
IsEnabled="{Binding Path=(local:AbstractSolutionItem.ContextMenuEnabled)}"
ItemContainerStyle="{StaticResource contextMenuStyle}"/>
在菜单中的每一项被绑定到一个IMenuItem对象(一个ViewModel所述菜单项)。当你点击菜单项时,它使用命令在基础对象上执行命令。这一切都很好。
但是,一旦命令在IMenuItem类上执行,它有时需要获取用户右键单击的对象的引用,以调出上下文菜单(或至少该对象的ViewModel)。这是上下文菜单的整点。我应该如何将树项目ViewModel的引用传递给MenuItem ViewModel?请注意,一些上下文菜单由树中的许多对象共享。
-1来源不能如果指定使用RelativeSource。运行时异常。 – 2012-03-20 18:18:34
DataContext =“{Binding PlacementTarget.DataContext,RelativeSource = {RelativeSource Self}}” – JoanComasFdz 2012-04-17 09:05:54