首页 > 解决方案 > 使用 ScrollView 创建用户控件

问题描述

我有一个 WPF 项目。

在这个项目中,我有一个带有 StackPanel 的 UserControl,其中包含各种元素。它位于网格中的一个单元格内。当我调整 Windwo 的大小并且单元格变得很小以适合 Stackpanel 时,我希望滚动视图接管。

我尝试将TheUserControl放在 a 中,但这似乎只适用于 Set size。我需要它来适应动态单元格大小。对于这样一个简单而常见的问题,我在网上找到的所有“解决方案”都是不必要的困难解决方法。所以我很确定有一种简单的方法可以实现这种行为。

伪代码

用户控件:

<UserControl x:class=x.TheUserControl>
    <StackPanel>
        <Label Content="Label 01 />
        <Label Content="Label 02 />
        <Label Content="Label 03 />
                     .
                     .
                     .
        <Label Content="Label n />
    </StackPanel>
</UserControl>

窗户:

<Window x:Class="x.MainWindow>
<Grid>

    <Grid.RowDefinitions>
       <RowDefinition Height="auto" />
       <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Label Content="Header" />

    <ScrollView Grid.Row="1">
        <x:TheUserControl />
    </ScrollView>

</Window>

当我将 StackPAnel 直接放入 ScrollView 时,我很确定 ScrollView 工作得很好,那么为什么中间有一个 UserControl 这么复杂呢?

我完全不知道 ScrollView 中的一些明显行为,如果有人可以向我展示更好的方法或解释为什么它会以这种方式表现,我会非常高兴。

标签: c#wpfuser-controlsscrollviewer

解决方案


请尝试在用户控件中使用 ScrollViewer 并使用 Horizo​​ntalScrollBarVisibility 和 VerticalScrollBarVisibility:

用户控制:

<UserControl x:Class="WpfApp1.TheUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             >
    <Grid>
        <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <StackPanel Orientation="Vertical"  Background="LightGray">
                <Label Content="Label 01" />
                <Label Content="Label 02" />
                <Label Content="Label 03" />
                <Label Content="Label n" />
            </StackPanel>
        </ScrollViewer>
    </Grid>
</UserControl>

主窗口:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" >
    <Grid Background="Aqua">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Label Content="Header" Grid.Row="0" />
        <local:TheUserControl Grid.Row="1" />

    </Grid>
</Window>

结果,如果您调整窗口大小:

内部带有 Scrollviewer 的用户控件


推荐阅读