C# 在添加到列表框的控件上激发的事件
我想知道将ListBoxItems添加到ListBox时会触发哪个事件。请注意,我不希望在数据更改时发生事件。我希望在添加控件时显示事件 我已经提到了这个答案,他们说当集合发生变化时,使用CollectionChaged事件。所以我不能使用它,因为它在控件添加到VisualTree之前触发 你可能在想我为什么需要这个。我只想将列表框的宽度更改为项目的最宽宽度。如果您对我试图实现的目标感兴趣,请查看我的代码:C# 在添加到列表框的控件上激发的事件,c#,wpf,C#,Wpf,我想知道将ListBoxItems添加到ListBox时会触发哪个事件。请注意,我不希望在数据更改时发生事件。我希望在添加控件时显示事件 我已经提到了这个答案,他们说当集合发生变化时,使用CollectionChaged事件。所以我不能使用它,因为它在控件添加到VisualTree之前触发 你可能在想我为什么需要这个。我只想将列表框的宽度更改为项目的最宽宽度。如果您对我试图实现的目标感兴趣,请查看我的代码: private void SomeEvent(object sender, ......
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;
}
}
您可以收听以下内容更改的项目集合:
public Window1()
{
InitializeComponent();
((INotifyCollectionChanged)mylistbox.Items).CollectionChanged += myListBox_CollectionChanged;
}
private void myListBox_CollectionChanged(object sender,NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (var item in e.NewItems)
{
}
}
}
另外,这里您将直接获取项目,而不是使用VisualTreeHelper,这里讨论的是如何控制大多数大小调整方面 首先定义一个新面板并覆盖方法
MeasureOverride
namespace CSharpWPF
{
class MyPanel : StackPanel
{
protected override Size MeasureOverride(Size constraint)
{
Size calculatedSize = base.MeasureOverride(constraint);
foreach (ListBoxItem item in this.Children)
{
//your logic with each item
}
return calculatedSize;
}
}
}
无论何时添加或删除任何项目,或需要更改布局(即调整容器大小),都将调用MeasureOverride方法
foreach(此.Children中的ListBoxItem)
假设您将仅与ListBox一起使用。您可以根据需要进行更改
然后将此新面板用作
<ListBox xmlns:l="clr-namespace:CSharpWPF">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<l:MyPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
通过这种方法,您可以更有效地控制大小
阅读更多关于
查看示例后,这里是您需要做的更改,以获得所需的
- 将边栏列表框设置为
Margin=“10,5,10,5”
- 将
添加到侧栏列表框HorizontalAlignment=“Right”
- 从metro.xaml第35行的ContentPresenter中删除
HorizontalAlignment=“Center”
- 设置metro.xaml 51号线
- 在第52行添加
<ListBox xmlns:l="clr-namespace:CSharpWPF">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<l:MyPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>