wpfmvvmdatagridtemplatecolumndatagridviewcheckboxcell

wpf bind checkbox command inside DataGridTemplateColumn.CellTemplate


This has been asked several times with different variations but I can't get any of them to work.

I'm trying to get a method called in my viewmodel when a checkbox (in a datagridTemplateColumn.cellTemplate) is clicked in my view

<DataGrid ItemsSource="{Binding TransactionTypes}" AutoGenerateColumns="False" CanUserAddRows="False" x:Name="TransTypesGrid">
<DataGrid.Columns>
    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                            Command="{Binding DataContext.UpdateCommand, ElementName=TransTypesGrid}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Header="Transaction Type" Binding="{Binding TransTypeDesc}" />
</DataGrid.Columns>

and in my viewModel

public DelegateCommand UpdateCommand { get; set; }

public myConstructor()
{    
  this.UpdateCommand = new DelegateCommand(Update);
}

private void Update()
{
    //this stuff works, it's just not getting called when a checkbox get's (un)checked
    //stuff that goes though the DataGrid's item source's IsSelected property
}

Solution

  • You should use Self binding in your command binding

    <DataTemplate>
       <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          Command="{Binding DataContext.UpdateCommand,RelativeSource={RelativeSource Mode=Self}}" />
    </DataTemplate>