0

Mainwindow constructor:

InitializeComponent();
MainViewModel = new MainViewModel();
captureUserControl.DataContext = MainViewModel.CaptureViewModel;

XAML in mainwindow

<UserControls:CaptureControl x:Name="captureUserControl"/>

Part of usercontrol

<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" >

Part of ViewModel

public BitmapSource MasterImage { get { return masterImage; } private set {SetValue<BitmapSource>(ref masterImage, value); } }

Error

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')

I think it might be because on creation the captureUserControl doesn't have its datacontext set until after its created. I want the MainViewModel to be instantiated in code behind because there's stuff that needs to be done that isn't a button click for example. Certain async 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?

Irwene
  • 2,807
  • 23
  • 48
shady
  • 1,076
  • 2
  • 13
  • 33
  • 1
    The DataContext of an element is inherited by it's children. Did you try without the ElementName in you usercontrol's binding ? A maybe related question : http://stackoverflow.com/questions/7262137/what-is-datacontext-for – Irwene Apr 17 '15 at 17:48
  • 1
    yep that did it ;/ you should post that as the answer. – shady Apr 17 '15 at 18:09

2 Answers2

1

The DataContext of an element is inherited by it's children.

The solution here is to remove ElementName from the Binding

A link for more details about DataContexts : What is DataContext for?

Community
  • 1
  • 1
Irwene
  • 2,807
  • 23
  • 48
0

UserControls were not designed to be bound to view-models.

They were meant to be bound to other containers (i.e. Window).

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118