WPF ListboxItem and ContextMenu

I have a code like this:

<ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" ContextMenuService.ShowOnDisabled="True"> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Command="Delete" Click="DeleteEvent"> </MenuItem> </ContextMenu> </StackPanel.ContextMenu> <TextBlock Text="{Binding EventName}"> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> 

Unfortunately this does not work. My context menu is disabled (it is displayed, but I cannot click it because it is disabled). I read that this problem is related to the selection problem, but I did not find a solution for this. Do you have ideas?

+6
source share
3 answers

Firstly, something strange is that you are trying to set the Command and the Click event. You must install one or the other. Perhaps the fact that the action is disabled is that you set the command with the value CanExecute = false;

Instead of writing a DataTemplate, you can try setting the ItemContainerStyle for the ListBoxItem as follows:

 <ListBox> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="Delete" Click="DeleteEvent"/> </ContextMenu> </Setter.Value> </Setter> <Setter Property="Content" Value="{Binding Path=EventName}"/> </Style> </ListBox.ItemContainerStyle> </ListBox> 

Here, I directly set the ContextMenu of the ListBoxItem instance so that it displays the menu in the right control.

+5
source

You just need to change the command to the header and handle DeleteEvent

  <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" ContextMenuService.ShowOnDisabled="True"> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Header="Delete" Click="DeleteEvent"> </MenuItem> </ContextMenu> </StackPanel.ContextMenu> <TextBlock Text="{Binding EventName}"> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> 
0
source

The ListBox already has a MenuContext. You can try it

  <ListBox x:Name="MyistBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Name}"/> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ContextMenu> <ContextMenu> <MenuItem Header="Update"/> <MenuItem Header="Delete"/> </ContextMenu> </ListBox.ContextMenu> </ListBox> 
0
source

Source: https://habr.com/ru/post/898060/


All Articles