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