I have 2 list views...and add/remove buttons between them.
On collection changed event of a list-view-collection in viewmodel, can i rollback the changes for a particular condition ?
You could handle the CollectionChanged
event of the ObservableCollection
to backup (via the VM or whatever) the old values (see NotifyCollectionChangedEventArgs.OldItems
property) and get them back when needed i.e. when user clicks 'Undo' etc.
Update In reference to comments bellow:
If you do want to rollback the collection from withing the CollectionChanged
event-handler, create a flag where you escape the handler from a recursive call (not tested with multi-threaded application), here is a simple example, you can easily tweak it to fit in your V/VM.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var x = new ObservableCollection<string>();
x.CollectionChanged +=
new NotifyCollectionChangedEventHandler(x_CollectionChanged);
x.Add("asdf");
x.Remove("asdf");
}
bool rollingBack = false;
void x_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (rollingBack) return;
if (e.Action == NotifyCollectionChangedAction.Remove)
{
if (e.OldItems.Contains("asdf"))
{
var oc = (ObservableCollection<string>)sender;
rollingBack = true;
oc.Add("asdf");
rollingBack = false;
}
}
}
Considering you get the sender of the event as an object (ie. the first parameter of the event) and the list of objects that were modified, yes you can do that. I wouldn't advise that though. If you encounter such a condition, provide a method on the ViewModel which is provided with the EventArgs
, and let it do the work. The view isn't the place to do logic.
Even better: check for the condition in the ViewModel itself (ie in the commands that are responseable for adding/removing)! The viewmodel is responseable for the state of the information, so keep your logic there. The view is just there to display the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With