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. 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:
<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...
精彩评论