WPF ListboxItem和ContextMenu [英] WPF ListboxItem and ContextMenu

查看:734
本文介绍了WPF ListboxItem和ContextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

<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?

推荐答案

首先,奇怪的是您试图设置Command和Click事件。您应该设置一个。也许禁用该操作的事实是因为您正在设置一个CanCan = false值的命令;

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;

您可以尝试设置ItemContainerStyle而不是编写DataTemplate像这样的ListBoxItem:

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>

在这里,我直接设置ListBoxItem实例的ContextMenu,这样它将在右侧控件上显示菜单。

Here I directly set the ContextMenu of the ListBoxItem instance so it will display the menu on the right control.

这篇关于WPF ListboxItem和ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆