WPF:如何重置/重新计算 ScrollViewer "ScrollableHeight"

标签 wpf scrollviewer

背景:

我正在为设置页面生成 UI。这些设置存储在字典中,因为每个相关对象的设置都不同。

问题:

ScrollViewerScrollableHeight 与内容的大小不准确。当 ScrollViewer 的内容更改时,ScrollableHeight 不会重置,而是附加新内容的高度。

时间:

我正在 Grid 中生成内容,它是 ScrollViewer 中的子元素。内容为 RowDefinitions,其中名称-值对显示为 TextBlocksTextBoxes。当选择不同的对象以编辑其属性时,网格的子项将被清除,并重新生成显示属性的 UI。正如我之前在问题定义中提到的,生成的内容的高度被附加到 ScrollViewer 的 ScrollableHeight 属性中。

我学到了什么:

我的第一个想法是清除 ScrollViewerScrollableHeight 并为添加的每一行附加行的高度以获得正确的大小。问题是无法设置 ScrollableHeight(私有(private) setter )。

代码:

XAML:

<ScrollViewer Name="svScroller"  Grid.Row="0">
    <Grid x:Name="gdPropertyGrid" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="35*" />
            <ColumnDefinition Width="65*" />
        </Grid.ColumnDefinitions>
    </Grid>
</ScrollViewer>

C#:

//Get Selected Item
var listBox = ((ListBox)sender);
var provider = listBox.SelectedItem as IProviderConfiguration;

if (provider != null)
{
    tbTitle.Text = String.Format("Properties for {0}",provider.Name);

    int rowCount = 0;

    PropertyGrid.Children.Clear();

    //Get properties
    foreach (var property in provider.Properties)
    {
        //Create Grid Row
        var rowDef = new RowDefinition() {Height = new GridLength(30)};
        PropertyGrid.RowDefinitions.Add(rowDef);

        //Create Name Label
        var tbPropertyName = new TextBlock { 
                Text = property.Key,
                VerticalAlignment = VerticalAlignment.Center 
        };

        //Create Value input
        var tbPropertyValue = new TextBox {
                Text = property.Value.ToString(), 
                VerticalAlignment = VerticalAlignment.Center
        };

        //Add TextBlock & TextBox Grid
        PropertyGrid.Children.Add(tbPropertyName);
        PropertyGrid.Children.Add(tbPropertyValue);

        //Set Grid.Row Attached property
        Grid.SetRow(tbPropertyName, rowCount);
        Grid.SetRow(tbPropertyValue, rowCount);

        Grid.SetColumn(tbPropertyValue, 1);

        rowCount++;
    }

 }

最佳答案

这是 ScrollViewer.ScrollableHeight 的预期行为,来自 MSDN:

Gets a value that represents the vertical size of the content element that can be scrolled.

也许您正在寻找 ScrollViewer.ViewPortHeight ?或者您可能正在寻找 ScrollViewer 在滚动之前拉伸(stretch)到某个点。在这种情况下,您需要考虑其他解决方案。

编辑

错误是您没有清除 RowDefinitions,因此 ScrollableHeight 似乎总是被附加,因为您不断添加新行!我的建议是您改用另一个列表框并采用主从模式。

关于WPF:如何重置/重新计算 ScrollViewer "ScrollableHeight",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1357293/

相关文章:

c# - 定位 UnhandledException 的来源

wpf - 绑定(bind) Observable 集合

c# - 将 ListBox 放入 ScrollViewer : mouse wheel does not work

windows-phone-7 - 将大文本放入 Textblock 和 ScrollViewer

c# - SHIFT + 滚动可在 ScrollViewer UWP 中水平滚动

C# wpf scrollviewer 不像windows store app那样工作

silverlight - 更改垂直滚动条的宽度

c# - 摆脱 try block 中的条件语句

c# - WPF DataGrid - 将数据项的属性绑定(bind)为 CommandParameter

c# - 在 WPF 中进行 DataBound 时将 TextBlock 设置为完全粗体