简体   繁体   中英

How to get Canvas to scroll in WinUI 3?

I am unable to get the ScrollBars to appear for a Canvas when its children are out of view. This is being directly added to the 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);
        }
    }

So, children are being added that go out of view horizontally and vertically. I've tried various settings for scrollbar visibility, alignments, etc. but just cant get the scrollbars to appear. Thanks for any inputs.

Specify a size for the Canvas so the ScrollViewer can measure it:

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);
    }
}

You may also want to enable horizontal scrolling:

<ScrollViewer HorizontalScrollBarVisibility="Auto">
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM