In a WPF application using a fairly standard MVVM pattern, I need to bind from a row in a DataTable (i.e. deep inside the visual tree) to the data context of the whole window. I am assuming the only way to do this is to use Mode=RelativeSource, but it requires that I specify the AncestorLevel.
- How do I determine the
AncestorLevel? - Why should I need to specify this at all when I know there is only ever one window? In other words, why can't I simply specify the type I want to bind to and have the binding engine reverse up the tree until it finds the first object of the required type?
- If I do figure out the
AncestorLevel, doesn't this make the code brittle? (If I change the nesting of the visual elements, it will obviously break.)
If there is no good solution involving RelativeSource, I thought I could take an alternative approach and 'propagate' the page-level property down through the logical tree to the individual items in the list. Is there an accepted pattern for this?
Has RelativeSource ever had a way of traversing up the tree searching only by type (or am I imagining this)?
See my question, similar issue was raised there:
WPF finding ancestor for binding
In short - when you give the ancestor type, it is searched upwards the elements tree until the ancestor of that given type is found (Level 1). Should you need to search two levels up (e.g. you have a grid in a grid and you're aiming for the "outer" grid), you specify
AncestorLevel=2and the ancestor is then a second element of that particular type while traversing the elements tree.