Wpf: FindAncestor of Ancestor

I have a UserControl related to ViewModel. In UserControl it is attached to the list of elements (class objects). Therefore, when I want to bind various elements to properties in the RowDetails DataGrid template, I use:

"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.SomeProperty}" 

It works great. Now I want to split the RowDetails stuff into a UserControl, which I can use in other top-level UserControls with DataGrids on them. So, how do I find UserControl, which is the ancestor of UserControl, in which this binding statement is written?

I cannot specify the top-level name of the UserControl in the x: Type declaration, because it is different every time.

+4
source share
2 answers

You can do this with AncestorLevel, however I seriously doubt that this is the correct way to bind.

You will have a UserControl that works depending on its position in the logical tree.

If you insert some other user control in the middle of the two, it will stop working.

The correct way to bind is to use the Datacontext that is provided to the control.

If it doesnโ€™t have some data than to adapt this datacontext file, even if it means reading it from the datacontext of its parent.

+4
source

Take a look at AncestorLevel .

 "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}, AncestorLevel=2}, Path=DataContext.SomeProperty}" 
+3
source

All Articles