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

前端 未结 5 706
深忆病人
深忆病人 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-07 23:41

    I had a similar problem with a custom-made visual.

    The solution was to defer the problematic task via Dispatcher (deferred execution with background priority in this case)...

    public void MyProblematicDisplayMethod(Symbol TargetSymbol)
    {
        this.HostingScrollViewer.BringIntoView(TargetSymbol.HeadingContentArea);
        ...
        // This post-call is needed due to WPF tricky rendering precedence (or whatever it is!).
        this.HostingScrollViewer.PostCall(
            (scrollviewer) =>
            {
                // in this case the "scrollviewer" lambda parameter is not needed
                var Location = TargetSymbol.Graphic.PointToScreen(new Point(TargetSymbol.HeadingContentArea.Left, TargetSymbol.HeadingContentArea.Top));
                ShowOnTop(this.EditBox, Location);
                this.EditBox.SelectAll();
            });
         ...
    }
    
    /// 
    /// Calls, for this Source object thread-dispatcher, the supplied operation with background priority (plus passing the source to the operation).
    /// 
    public static void PostCall(this TSource Source, Action Operation) where TSource : DispatcherObject
    {
        Source.Dispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(delegate(Object state)
                                            { Operation(Source); return null; }),
            null);
    }
    

    I've used that PostCall in other ScrollViewer related rendering situations.

提交回复
热议问题