我想知道当ListBox中添加ListBoxItems时触发的事件。请注意,我不希望在数据更改时触发事件,而是在控件添加时触发事件。
我已经参考了这个答案,他们说使用CollectionChanged事件,它会在集合更改时触发。所以我不能使用它,因为它在控件添加到VisualTree之前触发。
你可能会想为什么我需要这个。我只是想将listbox的宽度更改为最宽项的宽度。如果您对我要实现的内容更感兴趣,请查看我的代码:
我已经参考了这个答案,他们说使用CollectionChanged事件,它会在集合更改时触发。所以我不能使用它,因为它在控件添加到VisualTree之前触发。
你可能会想为什么我需要这个。我只是想将listbox的宽度更改为最宽项的宽度。如果您对我要实现的内容更感兴趣,请查看我的代码:
private void SomeEvent(object sender, ............... e)
{
double greatestWidth = 0;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(sidebar) - 1; i++)
{
ListBoxItem li = VisualTreeHelper.GetChild(sidebar, i) as ListBoxItem;
li.HorizontalAlignment = HorizontalAlignment.Center;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(sidebar) - 1; i++)
{
ListBoxItem li = VisualTreeHelper.GetChild(sidebar, i) as ListBoxItem;
if (li.Width > greatestWidth)
{
greatestWidth = li.Width;
}
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(sidebar) - 1; i++)
{
ListBoxItem li = VisualTreeHelper.GetChild(sidebar, i) as ListBoxItem;
li.HorizontalAlignment = HorizontalAlignment.Stretch;
}
}
更新:
class ResizablePanel : StackPanel
{
protected override Size MeasureOverride(Size constraint)
{
Size calculatedSize = base.MeasureOverride(constraint);
foreach (ListBoxItem li in this.Children)
{
li.HorizontalAlignment = HorizontalAlignment.Center;
}
double greatestWidth = 0;
foreach (ListBoxItem li in this.Children)
{
if (li.Width > greatestWidth)
{
greatestWidth = li.Width;
}
}
foreach (ListBoxItem li in this.Children)
{
li.HorizontalAlignment = HorizontalAlignment.Stretch;
}
calculatedSize = new Size(greatestWidth, calculatedSize.Height);
return calculatedSize;
}
}