背景:WPF:如何重置/重新计算的ScrollViewer “ScrollableHeight”
我产生了设置页面的用户界面。这些设置存储在字典中,因为每个对象的设置都会有所不同。
问题:
一个ScrollViewer
的ScrollableHeight
不是acurate的所述内容的尺寸。当ScrollViewer
的内容发生更改时ScrollableHeight
未被重置,而是追加新内容的高度。
当:
我一个Grid
,这是ScrollViewer
内的子元素中产生的内容。内容为RowDefinitions
,其中名称 - 值对显示为TextBlocks
和TextBoxes
。当为了编辑其属性而选择不同的对象时,网格的子项被清除,并且用于显示属性的UI被重新生成。正如我之前在问题定义中提到的,生成的内容的高度被附加到ScrollViewer
的ScrollableHeight
属性中。
我学到的东西:
我首先想到的是要清除ScrollViewer
的ScrollableHeight
和用于增加追加行的高度,以达到正确的大小每一行。问题是无法设置ScrollableHeight
(私人设置者)。
代码:
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++;
}
}
我会建议使用ListBox和DataTemplate,这比使用ScrollViewer和Grid更容易,你必须扰乱后面的代码。 – user7116 2009-08-31 13:06:35
同意,带有DataTemplate的ListBox确实可以提供优雅的解决方案。上述解决方案的目的是为了开发一个屏幕,该屏幕可以“匹配”网格中TextBlock TextBox对的其他屏幕。但是,你可以用DataTemplate实现这一点。我从来都不喜欢在C#中实现UI,因为它应该在XAML中。 如果情况发生变化,我会开发一个完整的PropertyGrid控件,或者使用像我看到的适合的开源实现,例如http://www.codeplex.com/wpg。谢谢 – holsee 2009-08-31 13:58:38