Search code examples
wpfxamlmvvmviewmodeldatacontext

Bind to MainWindow DataContext property from child control viewmodels property in main window data context viewmodel markup


  1. I have a UserControl (UC1) which has a data context : ViewModelOne.
  2. I have a MainWindow app that uses the UC1 as a child control.
  3. This MainWindow has a data context too : ViewModelTwo.

Need to bind a property in the view model's data context markup declaration, like this:`

<Window x:Class="control.controlnamespace" 
xmlns:vm="clr-namespace"..>
<Window.DataContext>
*<vm:ViewModelTwo Property="{Binding SomeProperty, ElementName=myControl}"/>* <-- Issue Here
</Window.DataContext>

<Grid>
   <UC1 x:Name="myControl"/>
</Grid>

That's where I am having the trouble no update is happening and the binding isn't happening either.


Solution

  • I found the solution for this:

    Setting up or trying to setup a property in the viewmodel's declaration inside the window datacontext markup is wrong and won't have any effect. This because by the time this context is set it's under a different thread therefore no updates or changes are being notified.

    WRONG --->

    <Window.DataContext>
    <vm:ViewModelTwo Property="{Binding SomeProperty, ElementName=myControl}"/>* <-- Issue Here
    </Window.DataContext>
    

    So the way to resolve this is to actually get the current loaded element (this could be user control, window etc) CORRECT -->

    <Window Name="myWindowName">
        <Window.DataContext>
             <vm:ViewModel />
         </Window.DataContext>
    
         <control:Control x:Name="myControl" PropertyToBind="{Binding Path=DataContext.Property, Mode=TwoWay, ElementName=myWindowName or myUserControlName}" >
    </Window>