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 CanBeDeleted
when the grid is changed.
<DataGrid AutoGenerateColumns="False"
ItemsSource="{Binding CurrentPosIn.PosInLocationsList}"
CanUserAddRows="{Binding UpdateEnabled}" CanUserDeleteRows="{Binding UpdateEnabled}" >
I'm using UpdateEnabled
for something different (profile permissions) and I don't want to make the DataGrid
read only either: I'd prefer (unless it is too complex) to see a blocking alert (a MessageBox
) preventing changes.
What I've done till now is
- against MVVM, because I've put the alert in the Model (but I can accept this, if it makes the changes quick and simple)
- not working, because the second part (see below) of my changes produces an invalid operation exception
The ViewModel contains the following list
[Association(ThisKey="Partita", OtherKey="Partita", CanBeNull=true, IsBackReference=true)]
public ObservableCollection<Model.PosInLocation> posin_locations_list = new ObservableCollection<Model.PosInLocation>();
public ObservableCollection<PosInLocation> PosInLocationsList {
get { return posin_locations_list; }
set {
posin_locations_list = value;
OnPropertyChanged( () => PosInLocationsList );
}
}
and I'm adding the consistency check here
string _storage;
[Column(Name = "storage"), PrimaryKey]
public string Storage {
get { return _storage; }
set {
if (this.loadedEF) {
string validate_msg;
if (!PurchasePosIn.CanBeDeleted(out validate_msg)) {
// against MVVM
MessageBox.Show(validate_msg, "Alert", MessageBoxButton.OK);
OnPropertyChanged( () => Storage );
return;
}
Persistence.MyContext.deletePosInLocation(this);
}
_storage = value;
OnPropertyChanged( () => Storage );
if (this.loadedEF) {
Persistence.MyContext.insertPosInLocation(this);
}
}
}
and here (second part)
internal void posin_locations_list_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
{
string validate_msg;
if (!CanBeDeleted(out validate_msg)) {
// indirectly produces an invalid operation exception
MessageBox.Show(validate_msg, "Alert", MessageBoxButton.OK);
return;
}
if (args.OldItems != null)
foreach(var oldItem in args.OldItems) {
if ( ((PosInLocation)oldItem).Partita != null)
Persistence.MyContext.deletePosInLocation((PosInLocation)oldItem);
}
if (args.NewItems != null)
foreach(var newItem in args.NewItems)
{
PosInLocation newPosInLocation = (PosInLocation)newItem;
if ( newPosInLocation.Partita == null) {
newPosInLocation.Partita = this.Partita;
newPosInLocation.PurchasePosIn = this;
newPosInLocation.loadedEF = true;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…