我有一个绑定到IList的DataGrid,并显示一个类型为Equipment的列表。我接下来创建了一个ContextMenu,它是DataGrid的一部分,它不具有命令,但我可以使用其他名称。我接下来要做的是选择DataGrid中的任何单个单元格,右键单击并在上下文菜单中选择一个新名称,并将数据网格中的当前值替换为上下文菜单中的当前标记/值。我使用MVVM模式这样做,所以使用MainWindow.xaml.cs中的代码不是一个有效的选项。
我是如何实现我的DataGrid并发布数据的。
MainWindow.xaml
{
<DataGrid Background="Gray" SelectionUnit="CellOrRowHeader" Grid.ColumnSpan="9" Grid.RowSpan"2" Name="equipmentGrid" VerticalScrollBarVisibility="Visible" ItemsSource="{Binding Path=EquipmentList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Equip Key" Binding="{Binding EquipKey}"/>
<DataGridTextColumn Header="Equip Name" Binding="{Binding EquipName}"/>
</DataGrid.Columns>
</DataGrid>
我如何实现我的ContextMenu
EquipmentIdFixViewModel
{
private IList<Emitter> Emitters;
....
public ICommand CreateContextMenuCommand
{
{
get
{
if(this._createContextMenuCommand == null)
{
this._createContextMenuCommand = new RelayCommand(a => this.CreateContextMenu(), p => this.CheckCondition());
return this._createContextCommand;
}
return this._createContextMenuCommand;
}
set
{
_this._createContextCommand = value;
OnPropertyChanged("CreateContextMenuCommand");
}
}
public ContextMenu EmitterContextMenu
{
get{return _emitterContextMenu;}
set{_emitterContextMenu = value; OnPropertyChanged("EmitterContextMenu");}
}
public void CreateContextMenu()
{
var contextMenu = new ContextMenu()
Emitters = new EmitterList().GetAll();
foreach (Emitter in Emitters)
{
MenuItem item = new MenuIten();
item.Header = emitter.EmitterName;
item.Tag = emitter;
item.Click += MenuItem_Click
contextMenu.Items.Add(item);
}
EmitterContextMenu = contextMenu;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var myObj = (Emitter)((MenuItem)sender).Tag;
Equipment et = this._grid.SelectedItem as Equipment; //Doesn't work.Ends up being null. Can't figure out how to capture the data from the DataGrid
et.EquipKey = myObj.EmitterName;
}
}
会发生什么是et is null。如何获取DataGrid中显示的信息的参考?