Object-To-Object Binding / ViewModel-To-ViewModel Binding

 

There may be times when you need to pass data back and forth between ViewModels in a loosly coupled way, without having to handle this in your ViewModels or code behind. Consider a parent-child ViewModel scenario, where your parent ViewModel may contain data resulting in the creation of multiple child ViewModels, for example the case when your parent ViewModel has a collection of business objects, and you need to enable editing each business object separately unsing their own View-ViewModels.

The XAML code below has an ItemsControl which binds to the Items collection of the ViewModel set as the DataContext of the parent View.
This will create an instance of the ChildView for each member of the Items collection.

<
ItemsControlItemsSource="{BindingPath=Items}"HorizontalAlignment="Center"VerticalAlignment="Center">
            <
ItemsControl.ItemTemplate>
                <
DataTemplate>
                   
<local:ChildView>
                  
</local:ChildView>
                </DataTemplate>
            </
ItemsControl.ItemTemplate>
        </
ItemsControl>

What we would like, is to pass each item in the Items collection to the ViewModel of each created ChildView so that an action can be taken based on that information.
In order to do this, we can create a binding which binds to a property of the ChildView ViewModel, and one binding that binds to the item from the parent ViewModel Items collection. Then, we need to tie those tow bindings together so that when one of the bound items changes, the other one gets updated as well.

A solution to this may look like this;

<ItemsControl ItemsSource="{Binding Path=Items}" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="{Binding}" Visibility="Collapsed" x:Name="HiddenTextBlock"/>
                        <local:ChildView>
                            <local:BindingBehaviors.ObjectToObjectBinding>
                                <local:ObjectToObjectBinding Source="{Binding Path=Text, ElementName=HiddenTextBlock}" Target="{Binding Path=MyProperty, Mode=TwoWay}"/>
                            </local:BindingBehaviors.ObjectToObjectBinding>
                        </local:ChildView>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

What we have done here is to create a binding behavior that ties a Source and Target binding together so that when the Source changes, the Target (MyProperty) gets updated as well. For this example to work, we needed to do a little “hack” by defining the Source binding to bind to a TextBlock which holds on to a member of the Items collection from the parent ViewModel (as the Items collection in this case happens to contain strings. If you need to store an Object, change the TextBlock to a ContentPresenter, for example, and bind to the Content property instead). The Target binding defines a binding to the MyProperty property of the ChildView ViewModel, so that MyProperty will get the value of the item from the Items collection when the ChildView is loaded.

Besides the BindingBehavior class that defines the ObjectToObjectBinding attached property, we need a class for our Source and Target bindings, and also a class that handles / relays the data updates between the Source and Target.

To hold on to our Source and Target bindings, we need a simple ObjectToObjectBinding class with only two properties;

public class ObjectToObjectBinding
    {
        public Binding Source { get; set; }
        public Binding Target { get; set; }
    }

The class that handles exchanging data between the Source and Target is also as simple as it gets; All it does is copy the value of the Source property to the value of the Target propery, and vica verca, when a change occurs.

public class DataRelay : DependencyObject
    {
        #region Source

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(object), typeof(DataRelay),
                new PropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));

        public object Source
        {
            get { return (object)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataRelay)d).OnSourceChanged(e);
        }

        protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            this.Target = e.NewValue;
        }

        #endregion

        #region Target

        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof(object), typeof(DataRelay),
                new PropertyMetadata(null, new PropertyChangedCallback(OnTargetChanged)));

        public object Target
        {
            get { return (object)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        private static void OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataRelay)d).OnTargetChanged(e);
        }

        protected virtual void OnTargetChanged(DependencyPropertyChangedEventArgs e)
        {
            this.Source = e.NewValue;
        }

        #endregion
    }


The code needed to tie the two bindings together is pretty simple;

private static void OnObjectToObjectBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ObjectToObjectBinding binding = e.NewValue as ObjectToObjectBinding;
            if (binding != null)
            {
                if (binding.Source == null)
                    throw new ArgumentNullException("binding.Source");
                if (binding.Target == null)
                    throw new ArgumentNullException("binding.Target");

                DataRelay dataRelay = new DataRelay();

                BindingBehaviors.SetObjectToObjectBindingRelay(d, dataRelay);

                BindingOperations.SetBinding(dataRelay, DataRelay.SourceProperty, binding.Source);
                BindingOperations.SetBinding(dataRelay, DataRelay.TargetProperty, binding.Target);
            }
        }

What we have done here, is created a private attached property called ‘ObjectToObjectBindingRelay’ which allows us to attach an instance of the DataRelay object to a DependencyObject (in this case, our ChildView).

Next, we sets the Source binding to update DataRelay Source property, and the Target binding to update the Target property, so that data is exchanged between the source and target object when data changes.

Download source code