【发布时间】:2020-11-30 14:25:35
【问题描述】:
我正在使用 c#、prism、wpf。我想在一个listview中动态创建一个上下文列表,如下图:
当我单击这些菜单项时,它将回调我的自定义函数。在该函数中,我可以识别单击了哪个菜单项,例如,我可以获取菜单项的标题。
我尝试添加命令标记并绑定到 ICommand。但是点击后没有任何反应。
我从网上阅读了不同的示例,但它们从未同时显示 xaml 和 viewmodel 的实现。我想问一下怎么办?非常感谢。
在 App.xaml.cs 中:
ViewModelLocationProvider.Register<MainWindowView, MainWindowViewModel>();
以下是我的 xaml:
<ListView Grid.Row="2" ItemsSource="{Binding ServiceObjects}" ItemContainerStyle="{StaticResource LstBoxItemStyleNormal}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding ServiceName}">
<TextBlock.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextMenuList}">
<ContextMenu.ItemTemplate>
<HierarchicalDataTemplate>
<MenuItem Header="{Binding MenuName}" Command="{Binding ConfirmButtonCommand}"/>
</HierarchicalDataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
以下是我的视图模型:
class MainWindowViewModel : BindableBase
{
public class MenuNode : BindableBase
{
private string _menuName;
public string MenuName
{
get => _menuName;
set => SetProperty(ref _menuName, value);
}
}
public class ServiceNode : BindableBase
{
private string _serviceName;
public string ServiceName
{
get => _serviceName;
set => SetProperty(ref _serviceName, value);
}
public ObservableCollection<MenuNode> ContextMenuList { get; } = new ObservableCollection<MenuNode>();
}
public ObservableCollection<ServiceNode> ServiceObjects { get; } = new ObservableCollection<ServiceNode>();
public MainWindowViewModel()
{
for (int i = 0; i < 10; i++)
{
ServiceNode tempNode = new ServiceNode { ServiceName = "AP", State = "Normal" };
tempNode.ContextMenuList.Add(new MenuNode { MenuName = "A Item" });
tempNode.ContextMenuList.Add(new MenuNode { MenuName = "B Item" });
tempNode.ContextMenuList.Add(new MenuNode { MenuName = "C Item" });
ServiceObjects.Add(tempNode);
}
ConfirmButtonCommand = new DelegateCommand(HandleConfirmButtonCommand);
}
public ICommand ConfirmButtonCommand { get; }
private void HandleConfirmButtonCommand()
{
}
【问题讨论】:
标签: c# wpf contextmenu prism