簡體   English   中英

WPF - 確定哪些控件在ScrollViewer中的Canvas中可見

[英]WPF - determine which control is visible in Canvas in ScrollViewer

我在xaml頁面中有這樣的東西:

<ScrollViewer x:Name="PreviewvideosScrollViewer" HorizontalScrollBarVisibility="Auto" Width="1366" Height="480" VerticalScrollBarVisibility="Disabled">
            <Canvas x:Name="VideoCanvas" HorizontalAlignment="Left">
            </Canvas>
</ScrollViewer>

在代碼中,我向畫布添加了許多控件,其中許多都不在窗口中。 如何確定哪些控件可見(用戶在屏幕中看到)以及哪些控件不可見?

我嘗試了這樣的示例代碼:

private bool IsUserVisible(FrameworkElement element)
    {
        if (!element.Parent.Equals(VideoCanvas))
            return true;
        //// position of your visual inside the scrollviewer    
        GeneralTransform childTransform = element.TransformToAncestor(VideoCanvas);
        Rect rectangle = childTransform.TransformBounds(new Rect(new Point(0, 0), element.RenderSize));

        ////Check if the elements Rect intersects with that of the scrollviewer's
        Rect result = Rect.Intersect(new Rect(new Point(0, 0), VideoCanvas.RenderSize), rectangle);
        ////if result is Empty then the element is not in view
        return result != Rect.Empty;
    }

或這個:

private bool IsUserVisible(FrameworkElement element, FrameworkElement container)
    {
        if (!element.IsVisible)
            return false;

        var bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
        var rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
        return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
    }

但兩者都不起作用。 哪里可能有問題? 在scrollviewer中使用畫布? 或者是其他東西? 謝謝

好吧,假設你在Canvas中擁有控制權。

你想獲得相對於ScrollViewer的坐標,然后你想檢查坐標是否在0和ScrollViewer.ViewportWidth和ScrollViewer.ViewportHeight之間。

你如何將Canvas cordinates轉換為ScrollViewer cordinates?

首先,我們不考慮滾動並假設Canvas小於ScrollViewer,其Horizo​​ntalAlignment設置為Left,VerticalAlignment設置為Top。

要獲得相對於ScrollViewer的控件,使用它很簡單:

var x = Canvas.GetLeft(YourControl);

var y = Canvas.GetTop(YourControl);

現在假設我們也應用了滾動。

var x = Canvas.GetLeft(YourControl) - ScrollViewer.HorizontalOffset;

var y = Canvas.GetTop(YourControl) - ScrollViewer.VerticalOffset;

if(x >= 0 && x <= ScrollViewer.ViewportWidth && y <= ScrollViewer.ViewportHeight)
  return true; // YAY

有道理,不是嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM