在WPF中,什么情况下不Visual.PointFromScreen抛出InvalidOperationException异常? [英] In WPF, under what circumstances does Visual.PointFromScreen throw InvalidOperationException?
问题描述
假设我想做到这一点,这样我就可以找到鼠标相对于视觉
,而无需访问特定的鼠标事件的当前位置:
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());
}
有时(通常当我只有两个选项卡控件之间切换) PointFromScreen
抛出 InvalidOperationException异常
与消息此Visual未连接到presentationSource。的
在看属性可在视觉
我看不到任何与一个 presentationSource
On looking at the properties available on Visual
I can't see any relating to a PresentationSource
.
给定一个视觉
,我怎么能知道它是要扔的时候我称之为异常 PointFromScreen
上它?
Given a Visual
, how can I tell if it is going to throw that exception when I call PointFromScreen
on it?
推荐答案
有一个静态方法<一href="http://msdn.microsoft.com/en-us/library/system.windows.$p$psentationsource.fromvisual.aspx"><$c$c>$p$psentationSource.FromVisual$c$c>其中:
There's a static method PresentationSource.FromVisual
which:
返回其提供的可视化是presented源。
Returns the source in which a provided Visual is presented.
我知道这并不能解决根本问题,但你可以检查视觉连接至presentationSource之前调用 PointFromScreen
。它将prevent例外,但你需要做一些更多的研究,为什么它没有被连接在首位。
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.
这篇关于在WPF中,什么情况下不Visual.PointFromScreen抛出InvalidOperationException异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!