Reputation: 6434
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?
Upvotes: 1
Views: 2991
Reputation: 3803
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.
Upvotes: 0
Reputation: 4071
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));
}
}
Upvotes: 0
Reputation: 34200
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).
Upvotes: 3