Wednesday, June 12, 2013

Intercepting RaisePropertyChanged

We've recently pushed an update which allows developers to intercept all MvxNotifyPropertyChanged notifications if you want to.

The aim of this is to allow you to provide custom RaisePropertyChanged functionality.

At this first release, the framework doesn't provide any standard Interceptors - but we might write an initial one at some point soon.


An example Interception

The core of interception is the IMvxInpcInterceptor interface.


    public interface IMvxInpcInterceptor
    {
        MvxInpcInterceptionResult Intercept(IMvxNotifyPropertyChanged sender, PropertyChangedEventArgs args);
    }


You might use this, for example, to provide things like automated additional notifications for certain types - e.g. you might use it to send dependent change notifications.

For example, suppose you have a Person ViewModel with properties:
  • FirstName
  • LastName
  • FullName

This new functionality would allow you to provide an interceptor which would automatically send a FullName change notification whenever FirstName or LastName change - ie.e you could implement this interceptor as:

    public class MyInterceptor : IMvxInpcInterceptor
    {
        public MvxInpcInterceptionResult Intercept(
                        IMvxNotifyPropertyChanged sender,
                        PropertyChangedEventArgs args)
        {
            if (sender.GetType () == typeof(Person)) 
            {
                if (args.PropertyName == "FirstName" ||
                    args.PropertyName == "LastName") 
                {
                    sender.RaisePropertyChanged ("FullName");
                }
            }

            return MvxInpcInterceptionResult.RaisePropertyChanged;
        }
    }



With this done you could then register your implementation with IoC during Setup.InitializeInpcInterception - e.g.

        protected override void InitializeInpcInterception()
        {
            Mvx.RegisterSingleton((
IMvxInpcInterceptor)new MyInterceptor());
        }


For release software, I wouldn't normally expect you to use this particular interceptor implementation, but I hope this illustrates how you might be able to use this mechanism.



For inspiration!


For some inspiration about the sort of thing that some people are doing in a similar area, take a look at the excellent: https://github.com/zleao/MvvmCross-PropertyChangedEventPropagation

No comments:

Post a Comment