[英]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 类构造函数的命令列表:
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 { };
}
通过按f5启动调试应用程序。 导航到页面并显示上下文菜单以在调试时重现错误
检查输出窗口中是否存在绑定错误( Menu->Debug->Windows->Output
)。 如果绑定有错误,则应在此处看到
您在哪里定义CommandList
属性? 它应该在您的“趋势”类中或您所说的任何类中
在字段初始值设定项中创建可观察集合的实例时,为什么在CommandList
属性上具有公共设置器? 这可能无法解决问题,但是通常您只添加或删除集合中的项目,或者不修改集合,而是始终设置集合的新实例。 您的课程允许同时使用,这闻起来很香
谢谢,将CommandList移到我的趋势模型可以解决它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.