简体   繁体   中英

Observable collection item property changed

I have a column class which uses view model base to implement INotifyPropertyChanged (lazy I know):

public class Column : ViewModelBase
{
    public string ColumnName { get; set; }
    public bool Anonymize { get; set; }
}

And then a list of columns:

public class Columns : ObservableCollection<Column>
{
}

In my view model I have a property columns and I am binding that to a combo box with a checkbox and textblock:

private Columns _tableColumns;
public Columns TableColumns
{
  get
  {
    return _tableColumns;
  }
  set
  {
    _tableColumns = value;
    OnPropertyChanged("TableColumns");
  }
}
  <ComboBox Name="cbColumns" ItemsSource="{Binding TableColumns}">
    <ComboBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <CheckBox  IsChecked="{Binding Anonymize, Mode=TwoWay}" />
          <TextBlock Text="{Binding ColumnName}"/>
        </StackPanel>
      </DataTemplate>
    </ComboBox.ItemTemplate>
  </ComboBox>

When I change the Anonymize property through the checkbox on an item, how do make the Columns property change in the view model to reflect this?

Your Column class needs to implement INotifyPropertyChanged (which you say it does). You also need to raise that event it when the value of Anonymize changes (which you don't).

If you want to change the Anonymize property only from the UI, you are done. If you'd like to see the changes(from the backend) on the UI, you have to implement the INotifyPropertyChanged interface in the Column class.

public class Column : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string columnName;
    public bool anonymize;

    public string ColumnName
    {
        get { return columnName; }
        set
        {
            columnName = value; RaiseOnPropertyChanged("ColumnName");
        }
    }
    public bool Anonymize
    {
        get { return anonymize; }
        set { anonymize = value; RaiseOnPropertyChanged("Anonymize"); }
    }

    public void RaiseOnPropertyChanged(string propertyName)
    {
        var eh = PropertyChanged;
        if (eh != null)
            eh(this, new PropertyChangedEventArgs(propertyName));
    }
}

When the Anonymize state changes it will need to notify the view model that it needs to modify the collection of columns. The way I've solved this before is to add a CheckChanged event to the Column class that is raised when Anonymize . The the view model subscribes to the event after it creates the Column object but it is added to the Columns collection. When CheckChanged is raised the view model adds/removes the item from the Columns collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM