0
votes

I have an ObservableCollection of items in which one of the property is bool. When i set the itemsSource of the datagrid as the ObservableCollection, it auto-generates the column with checkbox column for the bool property.

I would like to know how we can tick the checkbox in code, lets say if we have the mark all option?

I tried updating the ObservableCollection records property value with true, but it doesnt help updating the UI.

Please help.

[EDIT: Below code works as suggested in the answer] My Class is as follows

public class InvoiceDoc : INotifyPropertyChanged
    {   
        private bool _Selected;
        [DisplayName("Selected")]
        public bool Selected
        {
            get { return _Selected; }
            set { _Selected = value; this.OnPropertyChanged(); }
        }


        [DisplayName("Date")]                 
        public DateTime DocDate { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (PropertyChanged !=null)
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

}

The datagrid is as follows

<DataGrid x:Name="dgInvoices" Margin="32,110,32,59" AutoGeneratingColumn="dgInvoices_AutoGeneratingColumn"/>

setting the ItemsSource is as follows

 docs = new ObservableCollection<InvoiceDoc>(); ;

 dgInvoices.ItemsSource = docs;

I am expecting the grid to auto check the check box once is set the value in the collection.

1

1 Answers

0
votes

Binding to an ObservableCollection is only reactive if an Item is added or removed.

Your elements inside your Collection have to implement INotifyPropertyChanged so the UI recognises the changes

EDIT:

Lets say you have the following objects in your Collection:

public class MyClass {

  public string Name { get; set; }

  public bool IsActive { get; set; }

}

This class has now to be modified to the following:

public class MyClass : INotifyPropertyChanged{
  private string _name;
  private bool _isActive;

  public string Name
  {
    get { return this._name; }
    set { this._name = value; this.OnPropertyChanged();}
  }

  public bool IsActive
  {
    get { return this._isActive; }
    set { this._isActive = value;
      this.OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

If there are any Errors, remove the CallerMemberNameAttribute and invoke the this.OnPropertyChanged(); with the Propertyname.