我在绑定(bind)列表框项的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 >
命令 list :
private ObservableCollection<ContextMenuAction> commandList = new ObservableCollection<ContextMenuAction>();
public ObservableCollection<ContextMenuAction> CommandList
{
get
{
return commandList;
}
set
{
Set(ref commandList, value);
}
}
命令列表填写ViewModel类的构造函数:
CommandList.Add(new ContextMenuAction
{
Displayname = "Rename trend",
ContextMenuCommand = TrendRenameCommand
});
CommandList.Add(new ContextMenuAction
{
Displayname = "Remove trend",
ContextMenuCommand = TrendRemoveCommand
});
ContextMenuAction类:
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 { };
}
最佳答案
Menu->Debug->Windows->Output
)。如果绑定(bind)有错误,则应该在这里看到它CommandList
属性?它应该在您的“趋势”类中,或者您称之为CommandList
属性上具有公共(public) setter ?这可能无法解决问题,但是通常您只添加或删除集合中的项目,或者不修改集合,而是始终设置集合的新实例。您的类(class)允许两者都使用,而且闻起来有点淡
关于c# - MVVM列表框项目上下文菜单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31135237/