views:

53

answers:

2

I have a problem with commands in an MVVM application (I am only learning MVVM so go easy).

Valid XHTML

MyClassViewModel is set to the datacontext for MainForm1, MyList is bound to UserControl1 datacontext and each item in the list is represented by UserControl2. I am trying to fire MyCommand in UserControl2 using the following:

<CheckBox IsChecked="{Binding MyBool}" Command="{Binding Path=MyCommand}" CommandParameter="{Binding}">

I get the following error in the output:

System.Windows.Data Error: 39 : BindingExpression path error: 'MyCommand' property not found on 'object' ''MyObject''

From this error I know that WPF is looking for the command in the object bound to the UserControl2 what I really need is for it to look for the command in the MainForm1 datacontext (MyClassViewModel).

Is it possible to bubble up commands like this and if so how is it done?

Is bubbling up the command a good solution?

+1  A: 

This sounds like it might be the same problem:

http://stackoverflow.com/questions/642043/icommand-in-mvvm-wpf

Andrew Bienert
+1  A: 

Well it looks like your command is specific to UserControl2. So either you will have to add the ICommand to your MyObject (which is bound to UserControl2 as you said), or change the binding.
It makes sense that WPF throws you that binding error because UserControl2 has a DataContext 'MyObject', so it has no clue about a MyCommand specified in MyClassViewModel.

So either I would expand MyObject to contain the ICommand;
Or change the binding to something like this:

<CheckBox IsChecked="{Binding MyBool}" 
          Command="{Binding RelativeSource={RelativeSource FindAncestor, 
                    AncestorType={MainForm1}}, Path=DataContext.MyCommand}" 
          CommandParameter="{Binding}">

Not sure about the DataContext.MyCommand, could be that you can just use MyCommand.

Hope this helps!

Roel