FrameworkElement.Parent and VisualtreeHelper.GetParent behaves differently
Asked Answered
D

2

4

In a WP7 app, I used FrameworkElement.Parent recursively to determine whether a specific element is inside of another element. But it does not always work correctly. Then I changed my code to use VisualtreeHelper.GetParent method recursively, and it always work correctly(so far as I tested).

So what is the difference of them?

Thanks

Doubledealing answered 3/8, 2011 at 5:5 Comment(0)
M
4

Consider ControlA and ControlB where ControlA is a content control meaning it can contain other controls.

<ControlA>
   <ControlB />
</ControlA>

Logically the Parent property of the ControlB instance is an instance of ControlA in this case.

However if you were to look at Template setter of the default style of ControlA you may find complex Xaml containing some visual state management and a hierarchy of Borders and Grids and finally buried in that lot there is a ContentPresenter where the child control will be placed.

Recursively looping up VisualTreeHelper.Parent will find each element defined in the template from the ContentPresenter up to the "logical" parent element and then beyond.

Mediterranean answered 3/8, 2011 at 8:25 Comment(1)
meaning that VisualTreeHelper.GetParent returns the visual tree parent and FrameworkElement.Parent returns the logical tree parent?Quartile
T
1

"The value reported by the FrameworkElement.Parent property in Silverlight is generally the same value that would be reported by using VisualTreeHelper API, because the two tree concepts are frequently synchronized as far as how parent-child relationships are reported. However, there may be cases where FrameworkElement.Parent reports a parent that VisualTreeHelper does not."

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.parent(v=VS.95).aspx

Tunny answered 3/8, 2011 at 6:41 Comment(2)
I've read the document, but it does not explain when and why they behave differently.Quartile
I see exactly that. VisualTreeHelper.GetParent gives null while FrameworkElement.Parent is not null. This on WinRT though.Charleen

© 2022 - 2024 — McMap. All rights reserved.