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

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
devha
  • 3,307
  • 4
  • 28
  • 52
  • Does this answer your question? [WPF Databinding: How do I access the "parent" data context?](https://stackoverflow.com/questions/1127933/wpf-databinding-how-do-i-access-the-parent-data-context) – StayOnTarget Mar 03 '21 at 14:05

1 Answers1

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.

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 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} – devha Apr 22 '14 at 19:56
  • 5
    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? – Tseng Feb 20 '15 at 13:12