0

当 Canvas 的孩子不在视线范围内时,我无法让 ScrollBars 出现在 Canvas 上。这被直接添加到 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);
        }
    }

因此,正在添加水平和垂直方向看不见的儿童。我已经尝试了滚动条可见性、对齐方式等的各种设置,但只是无法让滚动条出现。感谢您的任何意见。

4

1 回答 1

1

为 指定一个大小,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">
...
于 2021-08-25T14:38:21.327 回答