I have a desktop app already released (so I\'d appreciate an answer that keeps the changes and regression tests at a minimum) and I need to add a consistency check Can
Maybe it's ugly (really, it's not so ugly: imho it's a nice MVVM approach, also applicable to modern mahapps.metro Dialogs), but now I'm setting
if (!CanBeDeleted(out validate_msg)) {
PurchaseItem.MessageBoxText = validate_msg;
an invisible TextBox
where I'm dispatching the alert
void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string alert = tb_message.Text;
if (alert != null && tb_message.Text.Length>0) {
Dispatcher.BeginInvoke(
(Action)(() => {
MessageBox.Show(alert, "Alert", MessageBoxButton.OK);
tb_message.Text = "";
}));
}
}
I see a connection with this other question Prevent adding the new Item on ObservableCollection.CollectionChanged event, in my case I'd say that prevent deleting is even more important. I don't know if there are more updated answers than this one (Can I rollback collection changes on collection changed event? which appears wrong) about this topic.
While the PropertyChanged can be easily raised to rollback an item update, for the collection changes I've been forced to pass and reference the view dispatcher inside the CollectionChanged event
PurchaseItem.dispatcher.BeginInvoke((Action)(() => RollBack(args)));
to rollback the added/deleted items
bool rollingBack = false;
private void RollBack(NotifyCollectionChangedEventArgs args) {
rollingBack = true;
if (args.Action == NotifyCollectionChangedAction.Remove)
{
foreach (var element in args.OldItems) {
PosInLocationsList.Add((PosInLocation)element);
}
}
if (args.Action == NotifyCollectionChangedAction.Add)
{
foreach (var element in args.NewItems) {
PosInLocationsList.Remove((PosInLocation)element);
}
}
rollingBack = false;
}