Reputation: 3641
Here is what i tried to do.. I want to provide an in place editing of products within a datagrid. Firstly i wrapped into a ObservableCollection a List<Product>
and implemented INotifyPropertyChanged interface for each POCO. Undoing changes and tracking what has changed in order to commit seems hard and i had lots of problems.. Also i feel that creating so many event handlers for every single poco when a property changed is not good strange...
So i am asking does DataTable solve these problems ? Even it solves what about validation ?It doesnt know anything about the POCO.... Are any other better solutions for this ??
Upvotes: 0
Views: 363
Reputation: 19885
DataTable do solve a few things...
DataView
.Having said that ...
INotifypropertyChanged
.Bindings
are easily achievable.So ultimately its your choice. However I dont mind observable collections and INotifyPropertyChanged notifications as they seem to get the best out of WPF DataGrid... styling and performance wise.
Upvotes: 1
Reputation: 132588
The property change handlers aren't that bad. Here's an example:
// Hook up a CollectionChanged event
ProductCollection.CollectionChanged += ProductCollection_Changed;
// In the Collection Changed event, hook up a PropertyChanged event
void ProductCollection_Changed(object sender, CollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach(Product item in e.NewItems)
item.PropertyChanged += Product.PropertyChanged;
}
if (e.OldItems != null)
{
foreach(Product item in e.OldItems)
item.PropertyChanged -= Product.PropertyChanged;
}
}
// In the Product property changed event, do something.
// Usually I only use this for raising the CollectionChanged event when
// a property of an object inside a collection changes.
void Product_Changed(object sender, PropertyChangedEventArgs e)
{
}
Personally, I would prefer to have each Product
track it's own changes, instead of tracking them in the ViewModel. When a product first gets created, keep a copy of the original data, and provide something like a UndoChanges()
method that simply reloads the original data.
To track changes on individual properties, I would do that in the set
method of each Product
property. This is because the PropertyChanged
event can be raised manually, and doesn't necessarily mean that the property has changed.
private int _someValue;
public int SomeValue
{
get { return _someValue; }
set
{
if (value != _someValue)
{
// Track what's changed here.
// How you do it is based on what you want to track
if (!ChangedProperties.Keys.Contains("SomeValue"))
{
ChangedProperties.Add(
new KeyValuePair<string, object>("SomeValue", _someValue));
}
_someValue = value;
RaisePropertyChanged("SomeValue");
}
}
}
Upvotes: 1