Introduction
In my current WPF project I quite regularly had to convert DataTables
into Lists of model classes, like this:
public void CreateExmapleModeList()
{
ExampleModels = new List<ExampleModel>();
foreach (DataRow row in tbl)
{
ExampleModel example = new ExampleModel
{
Name = row["Name"].ToString(),
Tag = row["Tag"].ToString(),
Value = double.Parse(row["Value"].ToString()),
// [...]
};
ExampleModels.Add(example);
example.PropertyChanged += ExampleModel_PropertyChanged;
}
}
assinging dozens of properties for dozens of lists is quite annoying, so I googled a little and found this quite handy answer on StackOverflow to assign properties dynamically, which cut down creating new lists to this:
ExampleModels = ListConverter.ConvertToList<ExampleModel>(tbl);
Problem
Now after refactoring my code I didn't know how to subscribe my custom PropertyChanged-Event to the PropertyChanged-Event of my model, so I simply iterated through the whole list again:
foreach (ExampleModel exmp in ExampleModels)
{
example.PropertyChanged += ExampleModel_PropertyChanged;
}
PropertyChanged:
public void ExampleModel_Propertychanged(object sender, PropertyChangedEventArgs e)
{
//do something
}
Question
I would much rather subscribe to the PropertyChanged-Event when creating the list rather then redundantly iterate a second time through the whole list.
Since there are quite a few Models, which have custom PropertyChanged-Events I need to subscribe them dynamically.
Is there a way simular to the RelayCommand for example:
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
m_execute = execute ?? throw new ArgumentNullException("execute");
m_canExecute = canExecute;
}
to tell my ContVertToList-Method which event it has to subscirbe like:
ExampleModels = ListConverter.ConvertToList<ExampleModel>(tbl, ExampleModel_Propertychanged(object sender, PropertyChangedEventArgs e));
and in ConvertToList
something like this:
public static List<T> ConvertToList<T>(DataTable dt, CustomPropertyChanged<S, E>) where T : TemplateModel
// [...]
objT.PropertyChanged = CustomPropertyChanged;
return onjT;
}).ToList();