My Model implements INotifyPropertyChanged
, and I have a WPF window bound to it (two way bindings).
I need to know when the model is being changed through the bound UI, so I could call an Update method from another module (which then copies My model to it's internal structures). Model can also be changed by another module.
How to tell (in my PropertyChanged
event handler) if the change originated in my UI, and not in that other module?
I do not want to call Update method if it was the other module that triggered the Pro开发者_开发技巧pertyChanged
event.
I'm fairly new to WPF myself, but the only immediately obvious way I can think of to do this would be to add extra set methods to the model, that modify the backing store without directly changing the property and thus firing the PropertyChanged event. To remove duplication, the property setter should probably call those methods as well and there should be a boolean argument fireChangedEvent. Something like this:
public string SomeThing
{
get { return _someThing; }
set { SetSomeThing(value, true); }
}
public void SetSomeThing(string value, bool fireChangedEvent)
{
_someThing = value;
if(fireChangedEvent)
{
NotifyPropertyChanged("SomeThing");
}
}
Then, in the other module, it would be
public void DoStuff
{
// ...
model.SetSomeThing("foo",false);
// ...
}
It's not an elegant method I know, and I hope someone else can think of something smarter, but I can't think of a good way of finding out from inside a property setter what exactly is setting that property.
Hopefully this is at least a workaround suggestion.
There is another way: using Binding.SourceUpdated
Every binding on the window would have to be set NotifyOnSourceUpdated=true
, and the common handler for SourceUpdated event would do the rest (raise the Window.ModelEdited
event that would trigger Update on another module).
精彩评论