Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind datagrid button mvvm

Tags:

c#

mvvm

wpf

xaml

I have datagrid, one of it's columns is buttons column, I want to bind this click to viewmodel, but it doesnt reach to the view model function.

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

And in the viewmodel:

public ICommand DeleteCommentCommand { get; private set; }
public MyViewModel()
{
   DeleteCommentCommand = new RelayCommand(Delete);
}

void Delete()
{
}

I have a feeling that the problem is in this line:

 <Button Command="{Binding DeleteCommentCommand}" >Delete</Button>
like image 473
Codey Avatar asked Sep 18 '25 05:09

Codey


1 Answers

DeleteCommentCommand is bound to DataGrid item DataContext, not to DataGrid DataContext itself (ViewModel). Your should set proper DataContext in CellTemplate or update binding a little bit, something like

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

You can also update your command and pass a parameter to RelayCommand and Delete method

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

void Delete(object item)
{
}

and pass the value in xaml CommandParameter="{Binding}"

like image 102
Pavel Anikhouski Avatar answered Sep 20 '25 20:09

Pavel Anikhouski