如果我使用自定义面板来布局我的 ListBoxItems,ListBox 不会尊重它们的组合高度(尽管它确实尊重它们的组合宽度) - 即使我的 ArrangeOverride 返回一个围绕所有项目的大小。
明确设置 ListBox 的高度可以使一切正常,但我希望它自己解决这个问题!
有没有人见过这个?
谢谢
更新:在下面的示例中,ListBox 使用了一个自定义面板,该面板根据 Row 属性垂直堆叠文章,并返回足够大的大小以包围所有文章。但除非我为 ListBox 设置高度,否则它会崩溃!
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication1">
<UserControl.Resources>
<DataTemplate x:Key="ArticleTemplate">
<TextBlock Text="{Binding Title}" />
</DataTemplate>
</UserControl.Resources>
<ListBox Height="200"
Background="AntiqueWhite"
ItemTemplate="{StaticResource ArticleTemplate}"
ItemsSource="{Binding}" VerticalAlignment="Top"
Margin="0,0,0,0">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<local:MyPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</UserControl>
这是面板:
public class MyPanel : Panel
{
protected override Size ArrangeOverride(Size arrangeSize)
{
double width = 0, height = 0;
foreach (UIElement child in this.Children)
{
var article = (Article)((ContentControl)child).DataContext;
var y = child.DesiredSize.Height * article.Row;
var location = new Point(0, y);
var rect = new Rect(location, child.DesiredSize);
child.Arrange(rect);
width = Math.Max(width, child.DesiredSize.Width);
height = Math.Max(height, y + child.DesiredSize.Height);
}
return new Size(width, height);
}
protected override Size MeasureOverride(Size availableSize)
{
foreach (UIElement child in this.Children)
{
if (child != null)
{
child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
}
}
return new Size();
}
}
和域类:
public class Article
{
private readonly int row;
private readonly string title;
public Article(string title, int row)
{
this.title = title;
this.row = row;
}
public int Row { get { return this.row; } }
public string Title { get { return this.title; } }
}