Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListboxItem and ContextMenu

Tags:

c#

.net

wpf

xaml

I have 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 It doesn't work. My context menu is disabled (it is displaying but I cannot click it because it's disabled). I've read that this problem is related to selection problem but I didn't find any solution for that. Do you have any ideas?

like image 801
radzio Avatar asked Sep 26 '11 11:09

radzio


1 Answers

Firstly, something strange is that you are trying to set Command and the Click event. You should set one or the other. Maybe the fact the action is disabled is because you are setting a Command with a value of CanExecute = false;

Instead of writing a DataTemplate, you can try to set the ItemContainerStyle for the ListBoxItem like this:

<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 it will display the menu on the right control.

like image 130
Ucodia Avatar answered Sep 23 '22 04:09

Ucodia