0

In my XAML I have a UserControl1 which I am trying to bind to the MainWindowViewModel of MainWindow:

<ControlLib:UserControl1 Hotzenplotz="{Binding Raeuber, ElementName=vm}" />

Hotzenplotz is a DependenyProperty of UserControl1. Raeuber is a property of MainWindowViewModel.

The catch is the ElementName=vm because I don't want XAML to look up the property in UserControl1 but in my MainWindowViewModel

If I bind my MainWindowViewModel like this everything is peachy:

<Window.DataContext>
    <local:MainWindowViewModel x:Name="vm" />
</Window.DataContext>

Unfortunately I can't instantiate MainWindowViewModel on-the-fly, I need to bind it from the code side. But then I cannot figure out on how to give the DataContext property the name vm for future reference.

Edit

I solved it this way. I added a name to the MainWindow

<Window x:Name="mw"

And access the binding with the help of the DataContext property

<ControlLib:UserControl1 Hotzenplotz="{Binding Path=DataContext.Raeuber, ElementName=mw}" />

But is this really the correct way?

Edit 2

The working code is available here: http://doena-soft.de/tmp/SubControls.zip

Dee J. Doena
  • 1,631
  • 3
  • 16
  • 26

1 Answers1

0

OK, I found the solution here: Binding between my usercontrol and ViewModel

I had the UserControl1 bound to its own DataContext like this:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Instead now I gave the UserControl1 inside its own XAML a name "uc" and referred all bindings there to this element name.

Inside UserControl1 before:

<Label x:Name="label1" Content="{Binding Hotzenplotz}" />

And after

<Label x:Name="label1" Content="{Binding Hotzenplotz, ElementName=uc}" />

For completeness' sake, here is the second solution: http://doena-soft.de/tmp/SubControls_better.zip

Dee J. Doena
  • 1,631
  • 3
  • 16
  • 26