views:

61

answers:

3

Hey all,

I am creating a wpf application and am having a little difficulty implementing an user interface idea I have.

I have a MasterViewModel bound to the MainWindow which exposes an observable collection of ViewModels. I have written some commands that essentially switch the current view model in the observable collection and this subsequently displays the corresponding view. However, when the application first loads, I add a HomeViewModel to the collection which shows the Home (Navigation) View. The problem I am having is the Commands I am binding against are exposed on the MasterViewModel so they aren't 'cascading' into the items control. Can anyone offer a solution or a better one? Many Thanks.

This is the error I am receiving:

System.Windows.Data Error: 40 : BindingExpression path error: 'MainWindowViewModel' property not found on 'object' ''HomeViewModel' (HashCode=5313339)'. BindingExpression:Path=MainWindowViewModel.LoadClientsCommand; DataItem='HomeViewModel' (HashCode=5313339); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

A: 

Can you provide code examples of your code scenario?

  1. This reminds me of Josh Smith's MVVM example (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx), mb you got your idea from there?
  2. If I understand you correctly: Why don't you write a VM for your ItemControl and put your commands in there?
  3. You could try to access the Commands from your ItemControl via RelativeSource (http://stackoverflow.com/questions/84278/how-do-i-use-wpf-bindings-with-relativesource)
Torsten
Yeah I tried to adapt my idea from here but the only problem is reaching outside of the user control to grab the commands.
aligray
+1  A: 

I believe you can access commands on the DataContext of your MasterViewModel through RelativeSource in the following way:

<Button>
    <Button.Command>
        <Binding Path="DataContext.MasterViewCommand">
            <Binding.RelativeSource>
                <RelativeSource
                    Mode="FindAncestor"
                    AncestorType="{x:Type MasterViewBaseClass}"
                />
            </Binding.RelativeSource>
        </Binding>
    </Button.Command>
    Click me!
</Button>
Jakob Christensen
A: 

Finally got it working, this is what I used in my View

Thanks for all your help!

<Button Command={Binding Path=DataContext.LoadClientsCommand, RelativeSource={RelativeSource AncestorType=Window}}" />

aligray
That's exactly what I wrote in my answer. Good for you :-)
Jakob Christensen
Oops! New to here... Marked as answer :)
aligray