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?
UPDATE:
It looks like this may be a timing issue. When I tried calling the TransformToAncestor
method inside an event handler rather than the value converter, it worked just fine. It seems that the value converter must be running as certain elements are instantiated before the ancestry relationship is established.
Not sure how to get around this, since I'm trying to use the MVVM pattern (and thusly don't really want to use event handlers, and would rather not have System.Windows stuff in my ViewModel).