如何在 WPF 中的画布周围显示滚动条



我有一个项目列表,我显示在画布上。我垂直显示这些项目,下一个在上一个下面,就像在列表框或列表视图中一样。

因为我需要能够拖动这些项目,为此我必须使用画布,因为 Canvas 允许我为项目设置具体位置。

集合中有许多项目在显示时超出窗口边界,为此我需要使用 ScrollViewer。这里的问题是,如果我不设置画布的高度,那么滚动查看器就不可见。

<ScrollViewer VerticalScrollBarVisibility="Auto"
              HorizontalScrollBarVisibility="Auto">
    <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Width="500" /> // Can't set Height here
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding Left}" />
                <Setter Property="Canvas.Top" Value="{Binding Top}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
</ScrollViewer> 

我该怎么做才能使画布周围的垂直滚动条可见?

因此,根据@EdPlunkett的回答,我想出了这个解决方案:

我向 ItemsControl 的 MinHeight 和 MinWidth 添加了绑定(尽管我想正常的高度和宽度也可以工作(。

<ScrollViewer VerticalScrollBarVisibility="Auto"
              HorizontalScrollBarVisibility="Auto">
    <ItemsControl ItemsSource="{Binding AlbumItems}" 
                  MinHeight="{Binding EditorHeight}" 
                  MinWidth="{Binding EditorWidth}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding Left}" />
                <Setter Property="Canvas.Top" Value="{Binding Top}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
</ScrollViewer>

在我的数据上下文中,我调用此方法来计算大小并将编辑器高度和编辑器宽度属性设置为它们的计算值。

    private void calculateEditorSize()
    {
        int maxEditorHeight = AlbumItems.Max((component) => component.Top + component.Height);
        int maxEditorWidth = AlbumItems.Max((component) => component.Left + component.Width);
        EditorHeight = maxEditorHeight;
        EditorWidth = maxEditorWidth;
    }

最新更新