11

This is a common situation in XAML based apps (WPF/Silverlight/WinRT).

WPF related link -> WPF Databinding: How do I access the "parent" data context?

RelativeSource with AncestorType, and Mode=FindAncestor usually comes to rescue in WPF.

Both of these are missing in WinRT API. How to access the Parent's (may not be immediate one), DataContext?

(I am aware of TemplateBinding, and ElementBinding but both are not suitable mostly in DataTemplate).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tilak
  • 30,108
  • 19
  • 83
  • 131

3 Answers3

20

I just had the same problem. Presumably this is common??

Here is a crude solution that works:

  • Bind the Tag property of a top level element to the DataContext

    <Grid Name="gridTop" Tag="{Binding}" />
    
  • Bind the property you want via ElementName in nested element, ie

    {Binding Tag.SomeProp, ElementName=gridTop}
    
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
LMK
  • 1,496
  • 1
  • 13
  • 15
  • 1
    Good suggestion, but this is [ElementBinding](http://www.rhyous.com/2010/04/13/tutorial-binding-one-element-property-to-another/). It does not work inside [DataTemplate](http://sblanco.wordpress.com/2010/01/29/wpf-bind-to-a-parent-datacontext-from-within-a-datatemplate/). Attached behavior seems to be the way to go. – Tilak Mar 15 '13 at 03:15
  • 1
    It does work inside DataTemplate - you are binding to the Tag of the (parent) Element, which has a reference to the parent DataContext. I use this all the time from inside DataTemplate elements to bind to the top level DataContext. – LMK Mar 19 '13 at 20:03
  • 13
    You can simplify this with removing the Tag and just use the datacontext directly {Binding DataContext.SomeProp, ElementName=gridTop} – matfillion Jul 02 '13 at 18:02
1

ElementName binding is still possible and might work in your case. Otherwise you'd need to implement an attached behavior.

Filip Skakun
  • 31,624
  • 6
  • 74
  • 100
0

There are several ways you can deal with this issue:

ElementName binding is the most common approach, as Filip pointed out.

You could walk visual tree till you find the parent. That is what FindAcestor does internally. You could dress it up in behavior for easy reuse.

If you use view models you could use messages instead of bindings or you could add parent context to each child view model.

Picking the best solution will depend on your specific circumstances.

Denis
  • 4,115
  • 1
  • 18
  • 20