【发布时间】:2010-02-21 22:10:48
【问题描述】:
我有一个 ViewModel (AbstractContextMenu) 代表我的上下文菜单 (IContextMenu),我使用 DataTemplate 将一个真正的 ContextMenu 绑定到它:
<DataTemplate DataType="{x:Type local:AbstractContextMenu}">
<ContextMenu x:Name="contextMenu"
ItemsSource="{Binding Path=(local:IContextMenu.Items)}"
IsEnabled="{Binding Path=(local:IContextMenu.IsEnabled)}"/>
</DataTemplate>
然后我有一个虚拟的 ConcreteContextMenu 用于测试,它只是继承自 AbstractContextMenu。 AbstractContextMenu 只是实现了这个接口:
public interface IContextMenu : IExtension
{
IEnumerable<IMenuItem> Items { get; set; }
bool IsEnabled { get; set; }
}
我将它用作另一个 ViewModel 对象的属性:
public IContextMenu ContextMenu
{
get
{
return m_ContextMenu;
}
protected set
{
if (m_ContextMenu != value)
{
m_ContextMenu = value;
NotifyPropertyChanged(m_ContextMenuArgs);
}
}
}
private IContextMenu m_ContextMenu = new ConcreteContextMenu();
static readonly PropertyChangedEventArgs m_ContextMenuArgs =
NotifyPropertyChangedHelper.CreateArgs<AbstractSolutionItem>(o => o.ContextMenu);
然后我将 StackPanel 绑定到该 ViewModel 并将 StackPanel 上的 ContextMenu 属性绑定到 ViewModel 的 ContextMenu 属性:
<StackPanel Orientation="Horizontal"
ContextMenu="{Binding Path=(local:AbstractSolutionItem.ContextMenu)}"
ContextMenuOpening="stackPanel_ContextMenuOpening">
<!-- stuff goes in here -->
</StackPanel>
当我运行它时,会触发 StackPanel 上的 ContextMenuOpening 事件,但不会显示 ContextMenu。我不确定我是否能做到这一点(使用 DataTemplate 将 ContextMenu 应用于 ContextMenu ViewModel)。有人知道吗?
【问题讨论】:
标签: wpf mvvm datatemplate contextmenu