我有一个自定义控件,它被用于ItemsControl的数据模板中。我想在每个项目上放置一个ContextMenu,并调用UserControl的视图模型来处理命令。使用下面的XAML,我可以让自定义控件上的单击事件调用用户控件视图模型中的SelectedItemCommand。但是,使用类似语法的上下文菜单会失败。默认情况下,每个自定义控件都会得到视图模式。我使用的任何RelativeSource语法值都无法解析为用户控件的视图模型(RelativeSource Self)。
魔术代码是什么?
魔术代码是什么?
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:MyCustomItem Width="Auto"
Command="{Binding DataContext.SelectedItemCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding}">
<controls:MyCustomItem.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
Header="Clear All" />
</ContextMenu>
</controls:MyCustomItem.ContextMenu>
</controls:MyCustomItem>
</DataTemplate>
</ItemsControl.ItemTemplate>