[英]Binding ContextMenu in DataTemplate
I have: 我有:
<ListBox>
<ListBox.Resources>
<DataTemplate DataType="{x:Type ViewModels:StyleViewModel}">
<DockPanel>
<Button Content="{Binding Name}" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Command="{Binding PlacementTarget.Tag.DataContext.RemoveMember1FavoriteStyleCommand}" CommandParameter="{Binding}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DockPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
What I'm trying to achieve is to bind the command in the menuitem of the context menu to an ICommand that is defined in a viewmodel that is the datacontext of the listbox, and the commandparameter should be the StyleViewModel, but what I tried didn't work. 我想要实现的是将上下文菜单的菜单项中的命令绑定到在视图模型中定义的ICommand,该视图模型是列表框的数据上下文,而命令参数应该是StyleViewModel,但是我尝试做的不是。工作。 Can anyone point me in the right direction?
谁能指出我正确的方向?
Found it! 找到了!
<ListBox ItemsSource="{Binding ActiveCustomer.Member1FavoriteStyles}" ItemsPanel="{StaticResource ListBoxStyleItemsPanelAsVerticalStackPanel}" ItemContainerStyle="{StaticResource ListBoxItemContainerStyle}" Background="Transparent" BorderThickness="0">
<ListBox.Resources>
<DataTemplate DataType="{x:Type ViewModels:StyleViewModel}">
<DockPanel>
<Button Content="{Binding Name}" Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Command="{Binding PlacementTarget.Tag.RemoveMember1FavoriteStyleCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" CommandParameter="{Binding}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DockPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
Almost working now, except that now CommandParameter="{Binding}" is not returning the StyleViewModel: 现在几乎可以正常工作,只是现在CommandParameter =“ {Binding}”不返回StyleViewModel:
<ListBox ItemsSource="{Binding ActiveCustomer.Member1FavoriteStyles}" ItemsPanel="{StaticResource ListBoxStyleItemsPanelAsVerticalStackPanel}" ItemContainerStyle="{StaticResource ListBoxItemContainerStyle}" Background="Transparent" BorderThickness="0">
<ListBox.Resources>
<DataTemplate DataType="{x:Type ViewModels:StyleViewModel}">
<DockPanel>
<Button Content="{Binding Name}" Tag="{Binding DataContext,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
<Button.ContextMenu>
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.Tag}">
<MenuItem Header="{Binding ActiveCustomer.Member1FirstName}" Command="{Binding RemoveMember1FavoriteStyleCommand}" CommandParameter="{Binding}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DockPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
I'm wondering if it can be done... 我想知道是否可以做到...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.