【问题标题】:How to get the ListBoxItem for an item in ListBox on "bind-time"如何在“绑定时间”上获取 ListBox 中某个项目的 ListBoxItem
【发布时间】:2011-04-10 02:55:08
【问题描述】:

我有一个带有 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...

【问题讨论】:

    标签: .net wpf data-binding listbox listboxitem


    【解决方案1】:

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

    ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
    

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

    protected void ItemContainerGenerator_StatusChanged(object sender, System.EventArgs e)
    {
        if (ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            EvaluateInitialElements(); 
    }
    

    【讨论】:

      【解决方案2】:

      当组件准备好渲染时触发事件OnRender,因此创建了ListBoxItem。对此事件进行过滤的初始处理似乎可以确保我需要的一切都准备好了。我评估并禁用元素,然后触发渲染:

      protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
      {
          EvaluateInitialElements();
          base.OnRender(drawingContext);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        • 2019-02-09
        • 1970-01-01
        相关资源
        最近更新 更多