我有一个包含对象集合和一堆命令的视图模型。
public class MainWindowVM : NotifyPropertyChangedBase
{
private CollectionViewSource employeeViewSource;
private ICommand cmdOpenDetailEmployee;
public MainWindowVM()
{
nsDataProviderEmployees = new NSDataProvider();
employeeViewSource = new CollectionViewSource();
cmdOpenDetailEmployee = new RelayCommand<object>((parameter) => {...});
this.LoadData();
}
public CollectionViewSource EmployeeViewSource => employeeViewSource;
public ICommand CmdOpenDetailEmployee => cmdOpenDetailEmployee;
}
在我的应用程序中,我想在显示员工的数据网格的上下文菜单中使用此命令。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyApp.UI"
xmlns:DataModel="clr-namespace:MyApp.DataModel;assembly=MyApp.DataModel" x:Class="MyApp.UI.MainWindow"
xmlns:vm="clr-namespace:MyApp.UI.ViewModels"
mc:Ignorable="d"
Title="MyApp - Main" Height="751.826" Width="1111.005" Loaded="Window_Loaded" Icon="Resources/MyApp.ico">
<Window.DataContext>
<vm:MainWindowVM />
</Window.DataContext>
<Grid x:Name="grdMain">
<DataGrid DataContext="{Binding Path=EmployeeViewSource}" x:Name="employeeDataGrid" EnableRowVirtualization="True" ItemsSource="{Binding}" Margin="10,77,10,0" RowDetailsVisibilityMode="VisibleWhenSelected">
<DataGrid.ContextMenu>
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">
<MenuItem Header="OpenDetail..."
Command="{Binding CmdOpenDetailEmployee}"
CommandParameter="{Binding}"/>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>...</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
问题,我无法提出绑定的组合,这两种绑定都使我无法将EmployeeViewSource
属性或ViewModel用作网格的DataContext和{{1} }属性,作为ContextMenu和MenuItems的DataContext。
根据所有帖子,我已经找到了这个应该的方法,但是单击菜单项时未执行命令。
答案 0 :(得分:0)
绑定到DataContext
的{{1}}的{{1}},然后让PlacementTarget
从窗口继承其ContextMenu
:
DataGrid