Twoway-bind view's DependencyProperty to viewmodel's property?

l33t picture l33t · Feb 28, 2013 · Viewed 18.7k times · Source

Multiple sources on the net tells us that, in MVVM, communication/synchronization between views and viewmodels should happen through dependency properties. If I understand this correctly, a dependency property of the view should be bound to a property of the viewmodel using two-way binding. Now, similar questions have been asked before, but with no sufficient answer.

Before I start analyzing this rather complex problem, here's my question:

How do I synchronize a custom view's DependencyProperty with a property of the viewmodel?

In an ideal world, you would simply bind it as this:

<UserControl x:Class="MyModule.MyView" MyProperty="{Binding MyProperty}">

That does not work since MyProperty is not a member of UserControl. Doh! I have tried different approaches, but none proved successful.

One solution is to define a base-class, UserControlEx, with necessary dependency properties to get the above to work. However, this soon becomes extremely messy. Not good enough!

Answer

Grx70 picture Grx70 · Feb 18, 2014

If you want to do it in XAML, you could try using styles to achieve that.

Here's an example:

<UserControl x:Class="MyModule.MyView"
             xmlns:local="clr-namespace:MyModule">
    <UserControl.Resources>
        <Style TargetType="local:MyView">
            <Setter Property="MyViewProperty" Value="{Binding MyViewModelProperty, Mode=TwoWay}"/>
        </Style>
    </UserControl.Resources>
    <!-- content -->
</UserControl>

In your case both MyViewProperty and MyViewModelProperty would be named MyProperty but I used different names just to be clear about what is what.