In WPF, under what circumstances does Visual.PointFromScreen throw InvalidOperationException?

前端 未结 5 695
深忆病人
深忆病人 2021-01-07 23:07

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:

<         


        
5条回答
  •  日久生厌
    2021-01-08 00:05

    Late to the ballgame, but these responses helped me. I just wanted to point out That PresentaionSources are not connected to visual elements until they are completely loaded. So if in your constructor you are setting up events that may get fired prior to the visual element you are attempting to call PointFromScreen on is ready to be displayed on screen, then you will get that error. While as mentioned before you can wrap your method in something like:

    public static Point GetMousePosition(this Visual relativeTo)
    {
        if(PresentationSource.FromVisual(relativeTo) != null)
           return relativeTo.PointFromScreen(GetMousePositionOnScreen());
        else
           return new Point();
    }
    

    you could also consider not calling your method until you are sure that the visual has been render on screen at least once.

提交回复
热议问题