【发布时间】:2013-06-16 22:44:26
【问题描述】:
我正在尝试将自动创建的菜单项的命令绑定到由父 MenuItem 的 ViewModel 公开的 ICommand。希望以下内容能很好地代表我所拥有的:
自定义控件:
class MyMenuItem : MenuItem {}
视图模型:
class ParentVM
{
public IEnumerable<ChildVM> Children { get; set; }
public ICommand TheCommand { get; set; }
}
class ChildVM
{
public string Name { get; set; }
}
自定义控件的全局样式:
<Style TargetType="namespace:MyMenuItem">
<Setter Property="Header" Value="Some Text"/>
<Setter Property="ItemsSource" Value="{Binding Children}"/>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="MenuItem"/>
<Setter Property="Command" Value="{Binding [parent].TheCommand}"/>
<Setter Property="Header" Value="{Binding Name}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
在上下文菜单中使用:
<ContextMenu>
<namespace:MyMenuItem DataContext="{Binding AParentVM}"/>
</ContextMenu>
我需要知道与 [parent] 相关的内容。确实创建了子菜单项并且它们的名称显示正确,这告诉我我在顶层有正确的 DataContext,因为“Children”绑定正确,而我在底层拥有正确的 DataContext,因为“Name”绑定正确。我希望使用 MyMenuItem 的 AncestorType 进行 RelativeSource 绑定,但它不起作用。
【问题讨论】:
标签: c# wpf xaml viewmodel datacontext