Share a property in the View (not ViewModel) between different UserControls

130 Views Asked by At

I have a View that displays something similar to a geographical map, and I have some UserControls inside this View, each of them displaying related info about the DataContext, but each one from a different perspective, so to say.

Then, my goal is to HOVER the mouse over one UserControl, highlighting a feature in EVERY UserControl, while of course the visual style of this highlight would be particular to each UserControl.

For example, if I have a Path in the map, and its elevation profile plotted in a graph, I would like to mouse over the elevation profile, dynamically displaying a vertical line over that graph, while at the same time some marker would be dynamically displayed in the map, and vice-versa.

I can do that by using some numeric value in the View itself, which would be two-way databound in each of the UserControls, but there are some conceptual problems:

  • Classic databinding pressuposes a property in the ViewModel, but the "mouse-highlight" feature is specific to the View (it does not represent object state), and I definitely wouldn't like to add such property to the ViewModel, that would contaminate it with View-specific code;
  • When UserControls are created, their DataContext is the ViewModel or some of its properties. Needing to change the DataContext of part of a UserControl to a different object doesn't seem an adviseable or easy way to do it;
  • I could hack a bit and create a Slider in the View with collapsed visibility, and use ElementBinding with each UserControl, but still then, how would I do ElementBinding between a View and a contained UserControl?

So, the main question is:

How can I bind a single property in the View (not in the ViewModel!) to many UserControls contained in that given View?

If everything were a single, monolithic View, using ElementBinding would be the obvious choice to me, but with different classes (one View and many UserControls) I don't know how to do ElementBinding, or even if it is the proper way to do what I want.

1

There are 1 best solutions below

1
On

I might be missing your question but why don't you simply add a Dependency Property to your View and bind it to the contained UserControls ?

<YourView x:Name="yourView">
 <YourUserControl SomePropertyOfYourUserControl="{Binding ElementName=yourView, Path="YourView's DependencyProperty"/>
 <YourSecondUserControl SomePropertyOfYourSecondUserControl="{Binding ElementName=yourView, Path="YourView's DependencyProperty"/>
</YourView>

--

Edit to complete my answer :

You said :

Classic databinding pressuposes a property in the ViewModel

..but it does not necessarly do so, as you can also bind to dependency properties in the View (in its codebehind).