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>
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With