0
votes

Here is my situation. I have a View and a ViewModel. The view's DataContext is set to the ViewModel. Due to the use of a 3rd party control, I am forced to put some code in the code-behind. In the code-behind I create an object called StraightConnectorTool.

In my View, I need to bind to this object. If the View's DataContext is set in the code-behind:

DataContext = this;

The following binding works fine.

<BarItemToolBehavior ActiveTool="{Binding ActiveTool, ElementName=diagram, Mode=TwoWay}" 
                                 Tool="{Binding StraightConnectorTool}"/>

Where diagram is the name of the 3rd party control on the View and ActiveTool is one of it's properties.

However, if the View's DataContext is set to the ViewModel, the binding doesn't work. I'm stuck trying to figure out how to bind to the view when it's DataContext is set to the ViewModel. Any ideas?

1
this.DataContext = this; is the cancer of WPF MVVM. This article explains why You'll note it's kinda long, but so is chemo.user1228

1 Answers

1
votes

It's not good practice, but you can bind the BarItemToolBehavior's DataContext to the view. Either by name in the code behind or in XAML using RelativeSource FindAncestor to find the view. A better solution would be to move that object to the VM where it belongs.