Search code examples
c#wpfdatagrid

How to instantly respond to PropertyChanged raised by Checkbox in Datagrid


I have the following code:

public class ViewModel
{
    private IServiceAccess _svcAccess;

     public ViewModel(IServiceAccess svcAccess)
     {
        _svcAccess = svcAccess;

     }

    public ObservableCollection<Item> ExistingItems
    {
        get
        {
            return new ObservableCollection<Item>(_svcAccess.GetExistingItems());
        }
    }

}

<DataGridTemplateColumn.CellTemplate>
  <DataTemplate>
    <CheckBox IsChecked="{Binding Path=Ignore, UpdateSourceTrigger=PropertyChanged}" />
  </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

I want to be able to instantly responsd when the User checks the box - Everywhere I've read this says it "updates the source", but how do I actually respond to that? The only other examples I've found have been the other way around, i.e. a change in the ViewModel raises the event to notify the View.

At the moment I've got an ObservableCollection in my ViewModel that is bound to the datagrid. Ignore is a field on my Item object, stored in the DB as a bool.

What I'd like to happen is checking the box triggers an event I can respond to in the ViewModel.

Note - I was going to map my EF entities into separate VM entities for the WPF layer, but was advised it was unecessary and overkill.


Solution

  • I'm slightly confused by your use of "ViewModel" in the question

    I've got an ObservableCollection in my ViewModel

    versus in the comment

    I've got checkboxes bound to a field in the VM

    Presumably these are 2 different VMs: a parent VM containing an observable collection of child VMs.

    I think you are stuck on thinking that the action has to take place in the parent VM. Simply change the field on the child VM to a property and do what you want in that property's setter. Of course if you want to call code in the parent from the child's setter, you can.