【问题标题】:Bind datagrid button mvvm绑定数据网格按钮 mvvm
【发布时间】:2019-08-11 10:17:53
【问题描述】:

我有数据网格,其中一个列是按钮列,我想将此单击绑定到视图模型,但它没有到达视图模型功能。

<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>

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    DeleteCommentCommand 绑定到 DataGrid 项目 DataContext,而不是 DataGrid DataContext 本身 (ViewModel)。您应该在 CellTemplate 中设置适当的 DataContext 或稍微更新绑定,例如

    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommentCommand}"
    

    您还可以更新命令并将参数传递给RelayCommandDelete 方法

    public MyViewModel()
    {
       DeleteCommentCommand = new RelayCommand(item => Delete(item));
    }
    
    void Delete(object item)
    {
    }
    

    并在 xaml CommandParameter="{Binding}" 中传递值

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      相关资源
      最近更新 更多