我有数据网格,其中一列是按钮列,我想将此单击绑定到视图模型,但它没有到达视图模型功能。<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding TableComments}" SelectedItem="{Binding SelectedRow}" x:Name="dataGrid" > <DataGrid.Columns > <DataGridTemplateColumn Header="Delete"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Command="{Binding DeleteCommentCommand}" >Delete</Button> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns></DataGrid>在视图模型中:public ICommand DeleteCommentCommand { get; private set; }public MyViewModel(){ DeleteCommentCommand = new RelayCommand(Delete);}void Delete(){}我感觉问题出在这一行: <Button Command="{Binding DeleteCommentCommand}" >Delete</Button>
1 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
DeleteCommentCommand绑定到 DataGrid item DataContext,而不是 DataGridDataContext本身(ViewModel)。您应该设置适当的 DataContextCellTemplate或更新一点绑定,例如
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommentCommand}"
您还可以更新命令并将参数传递给RelayCommand方法Delete
public MyViewModel()
{
DeleteCommentCommand = new RelayCommand(item => Delete(item));
}
void Delete(object item)
{
}
并在xaml中传递值CommandParameter="{Binding}"
- 1 回答
- 0 关注
- 95 浏览
添加回答
举报
0/150
提交
取消