WPF ListboxItem and ContextMenu

后端 未结 3 1468
感动是毒
感动是毒 2021-01-02 17:29

I have code like this:


    
        

        
相关标签:
3条回答
  • 2021-01-02 18:05

    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.

    0 讨论(0)
  • 2021-01-02 18:21

    You just need to change command to 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 讨论(0)
  • 2021-01-02 18:27

    ListBox already have 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 讨论(0)
提交回复
热议问题