我有一个数据网格,一些列显示为空白,后面的代码为空值。右键单击列,我们通过获取selectedrow来执行操作。如果我们在列中有空值,右键单击,行在rowcommand中为空。
任何想法,当selecteditem为null时如何仍然获取行?
XAML:
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn></DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit" ToolTip="Edit the inputs."
Command="{Binding DataContext.MenuEditRowCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}">
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
ViewModel:
public ICommand MenuEditRowCommand
{
get
{
if (_menuEditRowCommand == null)
{
_menuEditRowCommand = new ExceptionHandlingDelegateCommand<Class_NAme>(MenuEditRowMethod);
}
return _menuEditRowCommand;
}
}
private void MenuEditRowMethod(Class_NAme Inputs)
{
if (Inputs != null)
{
//
}
}
答案 0 :(得分:1)
为ContextMenu
容器定义DataGridRow
并绑定到其DataContext
:
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn></DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Tag" Value="{Binding Path=DataContext.MenuEditRowCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Edit" ToolTip="Edit the inputs."
Command="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
</MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
</DataGrid>