In WPF, under what circumstances does Visual.PointFromScreen throw InvalidOperationException?
.net-3.5, wpf
Solution
There's a static method `PresentationSource.FromVisual` which:
Returns the source in which a provided Visual is presented.
I know this doesn't solve the underlying problem, but you could check that the Visual is connected to a PresentationSource before calling `PointFromScreen`. It would prevent the exception, but you'd need to do some more investigation as to why it wasn't connected in the first place.
Problem
Suppose I wanted to do this, so I can find the current position of the mouse relative to a `Visual`, without needing access to a specific mouse event: ``` public static Point GetMousePosition(this Visual relativeTo) { return relativeTo.PointFromScreen(GetMousePositionOnScreen()); } ``` Sometimes (usually when I've just switched between two tab controls) `PointFromScreen` throws an `InvalidOperationException` with the message This Visual is not connected to a PresentationSource. On looking at the properties available on `Visual` I can't see any relating to a `PresentationSource`. Given a `Visual`, how can I tell if it is going to throw that exception when I call `PointFromScreen` on it?