2

I am using an MVVM approach, and I have an object from my ViewModel called DatabasesSubFrame which is DataTemplated to show a ListBox. I want to display a Button below the ListBox, which binds to both the currently SelectedItem, and a property on the DatabasesSubFrame object which is being DataTemplated.

I know how to refer to the currently selected item, by setting the DataContext on a shared ancestor with the ListBox and use {Binding /}. In this example the shared ancestor is a StackPanel. And if the DataContext wasn't explicitly set there I could easily bind to a property on the DatabasesSubFrame object by just doing {Binding SomeProperty}. However, if I do {Binding SomeProperty} within the explicitly set DataContext, it refers to the wrong DataContext.

How do I access the "original" DataContext here? I tried messing with RelativeSources and TemplatedParents but couldn't figure out how to fit them in.

<DataTemplate DataType="{x:Type VM:DatabasesSubFrame}"> <StackPanel DataContext="{Binding Databases}" > <ListBox Name="DbInfoBox" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <Label Content="{Binding ShortName}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!-- Problem: The Command and V:CreateCommandBinding.Command are set incorrectly here. How do I access OpenDbCommand from the top-level DataTemplate's DataContext? --> <Button Content="Open Database" CommandParameter="{Binding /}" Command="{Binding ???, Path=OpenDbCommand.Command}" V:CreateCommandBinding.Command="{Binding ???, Path=DataContext.OpenDbCommand}"/> </StackPanel> </DataTemplate> 
1
  • It looks like I can modify my data items to hold a reference to the parent viewmodel object, but that seems a bit hacky. Commented Nov 30, 2009 at 6:51

1 Answer 1

3

I think this question will help you to find the answer to yours. Another trick is to set the Name of the Window to something like "Root". You can then get at the window's original datacontext by using:

{Binding ElementName=Root, Path=DataContext.MyViewModelsProperty} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.