如何让 Canvas 在 WinUI 3 中滚动?

How to get Canvas to scroll in WinUI 3?

当 Canvas 的子项不在视图中时,我无法让 ScrollBars 出现。这是直接添加到 MainWindow。

<ScrollViewer>
    <Canvas x:Name="MainCanvas"/>
</ScrollViewer>

private void MainWindow_Activated(object sender, WindowActivatedEventArgs args)
    {
        for (int i = 0; i < 20; i++)
        {
            var rect = new Rectangle()
            {
                Height = 100,
                Width = 200,
                Stroke = new SolidColorBrush(Colors.Magenta)
            };

            Canvas.SetLeft(rect, (i * 200) + 10);
            Canvas.SetTop(rect, 10);

            var rect1 = new Rectangle()
            {
                Height = 100,
                Width = 200,
                Stroke = new SolidColorBrush(Colors.DarkOrchid)
            };

            Canvas.SetLeft(rect1, 10);
            Canvas.SetTop(rect1, (i * 100) + 10);

            MainCanvas.Children.Add(rect);
            MainCanvas.Children.Add(rect1);
        }
    }

因此,正在添加水平和垂直视野之外的子项。我已经尝试了滚动条可见性、对齐方式等的各种设置,但就是无法让滚动条出现。感谢您的任何意见。

Canvas 指定尺寸,以便 ScrollViewer 可以测量它:

private void MainWindow_Activated(object sender, WindowActivatedEventArgs args)
{
    MainCanvas.Width = 0;
    MainCanvas.Height = 0;

    for (int i = 0; i < 20; i++)
    {
        var rect = new Rectangle()
        {
            Height = 100,
            Width = 200,
            Stroke = new SolidColorBrush(Colors.Magenta)
        };

        double left = (i * 200) + 10;
        MainCanvas.Width = left;
        Canvas.SetLeft(rect, left);
        Canvas.SetTop(rect, 10);

        var rect1 = new Rectangle()
        {
            Height = 100,
            Width = 200,
            Stroke = new SolidColorBrush(Colors.DarkOrchid)
        };

        double top = (i * 100) + 10;
        MainCanvas.Height = top;
        Canvas.SetLeft(rect1, 10);
        Canvas.SetTop(rect1, top);

        MainCanvas.Children.Add(rect);
        MainCanvas.Children.Add(rect1);
    }
}

您可能还想启用水平滚动:

<ScrollViewer HorizontalScrollBarVisibility="Auto">
...