Logging value changes in WPF Databinding to a Property
I have a question about WPF databinding notification
I have a checkbox which is two-way binded to a bool propery of an internal data model. What I want is to show a value changed message in the UI (let's say "SomeBoolParameter changes from true => false" ) whenever the property is changed.
I have implemented the INotificationPropertyChanged interface in the data model and I know that I can ge开发者_如何学JAVAt notified by setting SourceUpdated in the XAML.
However, the EventArgs that I can received in the SourceUpdated event is a DataTransferEventArgs object, which I don't know how to retrieve the data model property value from it.
Of coz, I can place the logging code in the property setter... but definity it is an ugly solution. Any thoughts?
Why are you saying that it is an ugly solution? The setter is called each time you change the object value. If you want to follow an appropriate MVVM architecture, the only (and clean) way to do that is in the setter
As far as I know the DataTransferEventArgs has both a Property and a Source. Couldn't you just simply do something like this?
DependencyObject source = args.Source as DependencyObject;
if(source != null)
DoSomething(source.GetValue(args.Property));
Putting your logging code on the Setter isn't ugly. Your setters/getters should be generated by some sort of mechanism, either LInq2SQL, Entity Framework, or some other flavor or ORM, this means you can tweak the generator to put custom logging code on all setters.
If you don't use ORM, and you should allways use it, a more shiny solution is to use Interception, though it will feel like you're requesting a Tank to kill a fly. There's a very good article on using Interception with Unity 2.0 here.
精彩评论