我了解到如果一个网格行的高度,ScrollViewer
驻留,设置为Auto
, 垂直滚动条不会生效,因为 ScrollViewer
的实际大小可以大于视线的高度。因此,为了使滚动条工作,我应该将高度设置为固定数字或星形高度
但是,我现在有这个要求,我有两个不同的 View 驻留在两个网格行中,并且我有一个切换按钮来在这两个 View 之间切换:当一个 View 显示时,另一个 View 被隐藏/消失。所以我定义了两行,两个高度都设置为Auto
.我将每一行中 View 的可见性绑定(bind)到我的 ViewModel 的 bool 属性(一个从 True
转换为 Visible
,另一个从 True
转换为 Collapsed
。这个想法是当一个 View 的可见性是Collapsed
,网格行/ View 的高度将自动更改为 0。
View 显示/隐藏工作正常。但是,在一个 View 中,我有一个 ScrollViewer
,正如我提到的,当行高设置为 Auto
时,它不起作用.谁能告诉我如何在仍然拥有 ScrollViewer
的同时满足这样的要求?自动工作`?我想我可以在代码隐藏中设置高度。但由于我使用的是 MVVM,因此需要额外的通信/通知。有没有更直接的方法来做到这一点?
最佳答案
从 Auto
更改高度至*
, 如果你可以的话。
例子:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="525">
<StackPanel Orientation="Horizontal" Background="LightGray">
<Grid Width="100">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="_scroll1">
<Border Height="300" Background="Red" />
</ScrollViewer>
<TextBlock Text="{Binding ElementName=_scroll1, Path=ActualHeight}" Grid.Row="1"/>
</Grid>
<Grid Width="100">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="_scroll2">
<Border Height="300" Background="Green" />
</ScrollViewer>
<TextBlock Text="{Binding ElementName=_scroll2, Path=ActualHeight}" Grid.Row="1"/>
</Grid>
</StackPanel>
</Window>
关于wpf - 如何使滚动查看器在 WPF 中将高度设置为自动的情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19355818/