MVVM 列表框项目上下文菜单

MVVM listbox item contextmenu

我在绑定列表框项目的上下文菜单时遇到问题。构建后,我的上下文菜单不会显示任何项目。我搜索了很多但没有任何积极的结果。上下文菜单仍然是空的。请问您知道解决我的问题的方法吗?

感谢您的帮助。

列表框:

<ListBox Name="uxTrendListBox" ItemsSource="{Binding SignalGroup.Trends}" SelectedIndex="0" DisplayMemberPath="TrendName" SelectedValue="{Binding SelectedTrend}" FontSize="14" FontWeight="Normal" BorderThickness="0" Foreground="white" DockPanel.Dock="Top" Margin="10" Background="#FF5B5A5A">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu ItemsSource="{Binding CommandList}">
                            <ContextMenu.ItemTemplate >
                                <DataTemplate>
                                    <MenuItem Header="{Binding Displayname}" Command="{Binding ContextMenuCommand}" />
                                </DataTemplate>
                            </ContextMenu.ItemTemplate>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox >

命令列表:

private ObservableCollection<ContextMenuAction> commandList = new ObservableCollection<ContextMenuAction>();
        public ObservableCollection<ContextMenuAction> CommandList
        {
            get
            {
                return commandList;
            }
            set
            {
                Set(ref commandList, value);
            }
        }

填写ViewModel构造函数的命令列表class:

 CommandList.Add(new ContextMenuAction
        {
            Displayname = "Rename trend",
            ContextMenuCommand = TrendRenameCommand
        });
        CommandList.Add(new ContextMenuAction
        {
            Displayname = "Remove trend", 
            ContextMenuCommand = TrendRemoveCommand
        });

上下文菜单操作 class:

 public class ContextMenuAction : INotifyPropertyChanged
{
    private string displayName;

    public string Displayname
    {
        get { return displayName; }
        set
        {
            displayName = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Displayname"));
        }
    }

    private ICommand contextMenuCommand;

    public ICommand ContextMenuCommand
    {
        get { return contextMenuCommand; }
        set
        {
            contextMenuCommand = value;
            PropertyChanged(this, new PropertyChangedEventArgs("ContextMenuCommand"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
  1. 按 f5 启动调试应用程序。导航到页面并显示上下文菜单以在调试时重现错误

  2. 检查您的输出 window 是否存在绑定错误 (Menu->Debug->Windows->Output)。如果你在绑定时有错误,你应该在这里看到它

  3. 你在哪里定义了CommandList属性?它应该出现在您的“趋势”class 或任何您称呼它的地方

  4. 当您在字段初始值设定项中创建可观察集合的实例时,为什么您的 CommandList 属性 上有 public setter? 这可能不是问题所在,但通常您只能从集合中选择 Add/Remove 项,或者您不修改集合但总是设置集合的新实例。你的 class 两者都可以,而且闻起来有点