2

我有一个带有 Foo 对象的 ListBox,并且基于某些事件,我禁用/启用了 ListBox 中的 ListBoxItems。使用 ListBox.Items 属性,我找到了 Foo 对象,据我所知,我需要使用以下函数来获取 Foo 的 ListBoxItem 容器。正确的?

foreach (var item in Items)
{
    var lbi = ItemContainerGenerator.ContainerFromItem(foo) as ListBoxItem;
    // do something
}

实际上我有一个自定义控件 FilteringListBox 继承 ListBox 并为其添加了一个额外的属性。上面的代码在自定义控件后面的代码中,并且在创建 FilteringListBox 时工作得很好。然而,我的问题是,当某些属性被绑定时,我会尝试这样做。我有一个属性 FilteringCollection 和一个在绑定时触发的 PropertyCallback。在此回调中,我将存储 FilteringCollection,但我还将执行初始过滤 - 运行集合集合并禁用任何表示 FilteringCollection 中的 Foo 的 ListBoxItem。

这就是我遇到问题的地方。我找到了所有的 Foo,所以我验证了 ItemsSource 是否已设置,但是执行 ItemContainerGenerator.ContainerFromItem 我得到了 null。就像尚未创建 ListBoxItems 一样。不是吗?这是我的绑定:

<custom:FilteringListBox ItemsSource="{Binding AvailableFoos}" FilteringCollection="{Binding AlreadyIncludedFoos}"></custom:FilteringListBox>

所以; 要么:如何在“绑定时间”上获取 ListBoxItems?或者——如果我不能;是否有一些我可以覆盖的事件告诉我 ListBox 已完成创建 ListBoxItems?在没有运气的情况下尝试了 OnInitialized ......

4

2 回答 2

1

实际上,更好的解决方案似乎是使用ItemContainerGenerator。在创建时连接事件处理程序:

ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;

并让事件处理程序做需要做的事情:

protected void ItemContainerGenerator_StatusChanged(object sender, System.EventArgs e)
{
    if (ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        EvaluateInitialElements(); 
}
于 2010-09-12T20:40:16.180 回答
0

The event OnRender is triggered when the component is ready to be rendered, and hence the ListBoxItem's are created. Doing the initial handling of the filtering on this event seems to ensure that everything I need is ready. I evaluate and disable elements, and then trigger the rendering:

protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
    EvaluateInitialElements();
    base.OnRender(drawingContext);
}
于 2010-09-09T08:23:08.493 回答