c# - 使用 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 中的一些明显行为,如果有人可以向我展示更好的方法或解释为什么它会以这种方式表现,我会非常高兴。
解决方案
请尝试在用户控件中使用 ScrollViewer 并使用 HorizontalScrollBarVisibility 和 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>
结果,如果您调整窗口大小:
推荐阅读
- julia - Julia:计算排序数组中可能包含缺失的唯一元素数量的最快方法
- javascript - 物化 CSS 嵌套的 Scrollspy 不起作用:如何实现它?
- python - 当我每次在命令提示符中调用一个函数时,我该如何做到这一点,我不需要再次打开文件?
- c# - 如何将连续十进制值与不同捕获组中的可选子模式匹配分开?
- python - 刮 Naukri
- tensorflow2.0 - 错误:模块“tensorflow.python.framework.ops”没有属性“_TensorLike”
- html - 在换行符之前选择一个元素
- php - 带有 nginx 的 Laravel 返回内部服务器错误
- c++ - 为什么即使不涉及签名类型,std::push_heap 也会生成 -Wstrict-overflow=3 警告?
- sql - 根据另一列中的值拆分列中的数据