Bind to parent datacontext (out of itemsource)
Asked Answered
W

1

21

In my Windows Phone 8 app I have list of items. I have defined ItemTemplate for list items.

I want to display in each of these items one value from view model, not from the list item itself. How should I set up the binding from list item to viewmodel.

My data template is like this:

<DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding MyViewModel.Country ?? }"/> <!-- From view model -->
    </StackPanel>  
</DataTemplate>

So how to bind Country property to view model, not list item (in item source).

Weisberg answered 22/4, 2014 at 19:26 Comment(1)
Does this answer your question? WPF Databinding: How do I access the "parent" data context?Castro
A
48

Since you tagged your question with WPF, I can tell you the way of doing it in WPF, you can validate if that can be reused in Windows phone 8 apps.

First, you can give x:Name to root element to which ViewModel is bind to. Say it's window, set x:Name on it and bind using ElementName.

<Window x:Name="myWindow">
  ...
  <DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding DataContext.MyViewModel.Country,
                            ElementName=myWindow }"/> <!-- From view model -->
    </StackPanel>  
</DataTemplate>
</Window>

Second, you can try using RelativeSource to travel Visual tree and get root element DataContext.

<DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding DataContext.MyViewModel.Country,
                           RelativeSource={RelativeSource Mode=FindAncestor, 
                                                   AncestorType=Window} }"/>
                         <!-- From view model -->
    </StackPanel>  
</DataTemplate>

Moreove, if ListBox is inheriting DataContext from root element (i.e. you haven't explicitly set DataContext on ListBox). You can use both approaches on ListBox as well in place of Window.

Note - As mentioned here, FindAncestor is not defined for Windows phone 8 but element name does work. So, try using first approach and it should work for you.

Ardehs answered 22/4, 2014 at 19:35 Comment(2)
Thanks a lot Rohit! Im using caliburn micro and it looks that I make the binding work with out specifying view model. So this one works for me {Binding DataContext.Country, ElementName=myWindow}Weisberg
ElementName makes the templates not reusable and FindAncestor doesn't exist in WinRT/Windows Store Apps. How to bind the parent context in Windows Store Apps?Bodice

© 2022 - 2024 — McMap. All rights reserved.