I have a DataTable that I’m converting to a model which implements INotifyPropertyChanged.
This gets bound to a Listbox with a checkbox in it. When the checkbox is checked the PropertyChanged event fires. I want to handle this because I have a DataGrid that is bound to a DataTable. I want to filter that DataTable based on the checked items.
I would like to subscribe to the PropertyChange event in MainWindow.xaml.cs however I’m not sure how to do that as registering a handler in the constructor of my model would create X amount of handlers when I assume I only need one?
Here is what I have:
var categoryModel = ds.Tables[1].Rows.Cast<DataRow>()
.Select(x => x["Category"].ToString())
.Distinct()
.Select(y => new LanguageCategory { CategoryName = y, IsChecked = true });
public class LanguageCategory : INotifyPropertyChanged
{
private string categoryName;
private bool isChecked;
public event PropertyChangedEventHandler PropertyChanged;
public string CategoryName
{
get { return categoryName; }
set
{
categoryName = value;
NotifyPropertyChanged("CategoryName");
}
}
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
NotifyPropertyChanged("IsChecked");
}
}
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
You want the MainWindow to be notified when one of the
LanguageCategorys is checked.You have two choices.
1) When you create your list of
LanguageCategorys, subscribe to each of their PropertyChanged events. You must remember to unsubscribe from them when you recreate your list.2) Create a callback method in MainWindow and pass in a delegate to it when you create each LanguageCatagory. The LanguageCategory can call this when its IsChecked is changed. This is similar to JesseJame’s answer but doesn’t involve another class.
The advantage of this over 1 being that no cleanup is required when the list changes.
Example code for 2)