Dataform edit mode & navigating away from the page. MVVM Silverlight
Using SL4 in MVVM.
When I have a dataform in edit mode, and I navigate to another page, I'm getting errors related to an attempt to RaisePropertyChanged (Object reference not set to an instance of an object).
I found this and implemented it, in an attempt to fix the problem. My Dataform is definitely hitting my CancelEdit function (part of my IEditableObject implementation, located in the base class for all of my models).
I've also initialized all of my nullable declarations/backer variables with appropriate values (e.g private decimal _GeneralOverhead = 0.0M) so I'm really puzzled by what's not being set to an instance of an object. The error occurs after the following steps:
1) Pull up data form & click 'edit item' button
2) Edit a value开发者_如何学Go in one of the fields 3) navigate to another pageAt this point, I call cancel edit in my EditableModelBase (implementing IEditableObject). From here, this is hte code:
4) Inside EditableModelBase:
public void CancelEdit()
{
foreach (var info in CurrentModel.GetType().GetProperties())
{
if (!info.CanRead || !info.CanWrite) continue;
// if (info.Name == "StatusCodeString" || info.Name == "StatusCodeImage" || info.Name == "StatusCodeColor") continue;
var oldValue = info.GetValue(Cache, null);
CurrentModel.GetType().GetProperty(info.Name).SetValue(CurrentModel, oldValue, null);
}
}
On the first iteration through my foreach loop, when its hitting the .SetValue(CurrentModel) line, it calls up my model. Now, each of the props in my model RaisePropertyChanged, because otherwise my dataform doesn't recognize that it's been changed (thereby allowing the 'cancel' button to enable itself). When RaisingPropertyChanged is fired, it calls this code block:
protected virtual void RaisePropertyChanged(string propertyName)
{
VerifyPropertyName(propertyName);
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I've tried throwing in checks on handler & the 'new PropertyChangedEventArgs' and they both are instantiated. The only thing I can think of is the fact that my 'this' object is set to (in this case) my Models.Transactions model. Even if that's true, I'm not sure how to fix it. Any ideas?
From what I see from your post I would assume that one of the properties you are loking for is not there. To minimize the risk and maybe fix the problem I'd suggest the following implementation:
public void CancelEdit() {
foreach (var info in CurrentModel.GetType().GetProperties()) {
if (!info.CanRead || !info.CanWrite) continue;
// if (info.Name == "StatusCodeString" || info.Name == "StatusCodeImage" || info.Name == "StatusCodeColor") continue;
var oldValue = info.GetValue(Cache, null);
var property = CurrentModel.GetType().GetProperty(info.Name);
if (property != null)
property.SetValue(CurrentModel, oldValue, null);
}
}
精彩评论