2

I need to access DataContext of parent in wpf xaml. The whole xaml page code is dynamic. So don't know about the type of parent.

I am writing this

<Grid DataContext={Binding Path=.}>

Is this correct?

techfun
  • 913
  • 2
  • 13
  • 25
  • 1
    Try it - if its work its correct – MikroDel Nov 27 '12 at 11:01
  • 1
    Possible duplicate: [WPF Databinding: How do I access the “parent” data context?](http://stackoverflow.com/questions/1127933/wpf-databinding-how-do-i-access-the-parent-data-context) – khellang Nov 27 '12 at 11:07

1 Answers1

6

Remember that if DataContext is not explicitly set, it will inherit its parent's DataContext. If, for some reason, this doesn't work, you should take a look at binding with RelativeSource.

Something like this might work:

<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext}}"

Given that the Grid has an ancestor of type Window (which I think all controls should have).

khellang
  • 17,550
  • 6
  • 64
  • 84
  • Thanks. By default it works. Just want to know for knowledge if the AncestorType is not Window for the parent and I set Binding as you mentioned, then what will happen? – techfun Nov 27 '12 at 12:45
  • 1
    If you specify `AncestorType` of `Window` and the element has no ancestors of type `Window` (which I guess will never happen) the binding will simply not work. This is the same behavior you get when binding to a `Path` which does not exist. Again, read the [RelativeSource MarkupExtension documentation](http://msdn.microsoft.com/en-us/library/ms743599.aspx), it will tell you everything there is to know about `AncestorType` and `AncestorLevel`... – khellang Nov 27 '12 at 12:52