Error when using TransformToAncestor: "The specified Visual is not an ancestor of this Visual."
- by Brian Sullivan
I'm trying to get the offset of a control relative to the top of its window, but I'm running into trouble when using the TransformToAncestor method of the control. Note: this code is in a value converter which will convert from a control to its relative Y position in relation to the window.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var ctrl = (Control) value;
var win = Window.GetWindow(ctrl);
var transform = ctrl.TransformToAncestor(win); // Exception thrown here.
var pt = transform.Transform(new Point(0, 0));
return pt.Y;
}
The call to Window.GetWindow works just fine, and returns the correct window object inside which the control resides.
Am I misunderstanding what WPF thinks of as an "ancestor"? I would think that given the result of GetWindow, that window would be an ancestor of the control. Are there certain nesting patters that would cause the line of ancestry to be cut off at a certain point?