title: WPF bind usercontrol to viewmodel from code behind
body: <p><strong>Mainwindow</strong> constructor:</p>
  
  <pre><code>InitializeComponent();
  MainViewModel = new MainViewModel();
  captureUserControl.DataContext = MainViewModel.CaptureViewModel;
  </code></pre>
  
  <p><strong>XAML</strong> in <strong>mainwindow</strong></p>
  
  <pre><code>&lt;UserControls:CaptureControl x:Name="captureUserControl"/&gt;
  </code></pre>
  
  <p>Part of <strong>usercontrol</strong></p>
  
  <pre><code>&lt;Image x:Name="masterImage"  Margin="0,189,0,120" RenderTransformOrigin="0.5,0.5" Source="{Binding Path=MasterImage, ElementName=captureUserControl}" Stretch="Fill" Grid.Column="1" &gt;
  </code></pre>
  
  <p>Part of <strong>ViewModel</strong></p>
  
  <pre><code>public BitmapSource MasterImage { get { return masterImage; } private set {SetValue&lt;BitmapSource&gt;(ref masterImage, value); } }
  </code></pre>
  
  <p><strong>Error</strong> </p>
  
  <pre><code>System.Windows.Data Error: 40 : BindingExpression path error: 
  'MasterImage' property not found on 'object' ''CaptureControl' 
  (Name='captureUserControl')'. BindingExpression:Path=MasterImage; 
  DataItem='CaptureControl' (Name='captureUserControl'); 
  target element is 'Image' (Name='masterImage'); target property is 'Source' (type 'ImageSource')
  </code></pre>
  
  <p>I think it might be because on creation the <code>captureUserControl</code> doesn't have its datacontext set until after its created. I want the <code>MainViewModel</code> to be instantiated in code behind because there's stuff that needs to be done that isn't a button click for example. Certain <code>async</code> methods need to be called on window load to initialize hardware. Does anyone have any examples or tips of the data bindings set up in this way?</p>