0

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

zx485
  • 28,498
  • 28
  • 50
  • 59
aligray
  • 2,812
  • 4
  • 26
  • 35

2 Answers2

2

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
  • 14,826
  • 2
  • 51
  • 81
1

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 (How do I use WPF bindings with RelativeSource?)
Community
  • 1
  • 1
Torsten
  • 1,696
  • 2
  • 21
  • 42
  • 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 Jul 26 '10 at 10:05