我需要在列表框和面板之间实现一些东西。它必须有没有自己风格的可绑定项目源。所以我决定从FrameworkElement派生。我试图在我的控件后面的代码中添加新按钮,并在更改 ItemsSource 属性时调用 InvalidateMeasure。在 MeasureOverride 方法中,我运行 itemssource 集合并使用 availableSize 作为每个项目的参数调用 Measure。但结果我得到了itemssouce内控件的奇怪DesiredSize(在我的情况下是按钮) - 16高度和0宽度。这是我的代码:
// part from usercontrol's code behind
public MainPage()
{
InitializeComponent();
dash.ItemsSource.Add(new Button { Content = "button 1 content", Padding = new Thickness(10) });
dash.ItemsSource.Add(new Button { Content = "button 2 content", Padding = new Thickness(10) });
}
//part from my control
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = new Size();
foreach (UIElement item in ItemsSource)
{
item.Measure(availableSize);
desiredSize.Height += item.DesiredSize.Height;
desiredSize.Width += item.DesiredSize.Width;
}
return desiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
double x = 25, y = 25;
foreach (FrameworkElement item in ItemsSource)
{
item.Arrange(new Rect(x, y, item.DesiredSize.Width, item.DesiredSize.Height));
}
return base.ArrangeOverride(finalSize);
}
我尝试手动设置项目的高度和宽度,但没有帮助。甚至尝试使用 new Size(double.PositiveInfinity,double.PositiveInfinity); 第一次调用 Measure 两次 无论如何,按钮都不想出现在用户控件上。
请帮助我确定我做错了什么!