开发者

When are ListBoxItems created for ListBox?

I have a ListBox that I bind to an ItemsSource, like this:

var foos = new ObservableCollection<Foo> { foo1, foo2, foo3 };
var listBox = new ListBox { ItemsSource = _foos };

Now I want to do some operations right away on the ListBoxItems that holds the items, but they don't seem to be created right away. Are they? Is there some event I can listen to in order to be notified, or am I simply trying to fetch the ListBoxItem's in an invalid way? I am doing it like this (and have verified that it works somewhere I know the ListBox is "ready"):

var lbi = listBox.ItemContainerGenerator.ContainerFromItem(foo1) as ListBoxItem;

Note that this is being done in a unit test, so I guess the ListBox is never rendered. Is that why 开发者_如何学编程the ListBoxItems aren't created? And can I manually trigger the creation of the ListBoxItems somehow?


Items-creation is done async and depending on the panel, it can happen that it is not created at all (virtualization). The event your're looking for is ItemContainerGenerator.StatusChanged. Do a google-search for it on SO, you will find many examples. However directly searching and working with the items can get complex.

Here is a very good article that discusses the item-creation in detail. Look also for the ancestor-article .

BTW: I recommend you to look at the MVVM-pattern. While there is a small bit of time you loose learning it (not comparable to the time learnding WPF), it will save you a lot of time. Here you find a link to a video from Jason Dolinger that gives you a great start-point.

Update:

As promised in the comment, here a function to search the visual tree (only usable when virtualization is off).

void FindChildFrameworkElementsOfType<T>(DependencyObject parent,IList<T> list) where T: FrameworkElement{             
    DependencyObject child; 
    for(int i=0;i< VisualTreeHelper.GetChildrenCount(parent);i++){             
        child = VisualTreeHelper.GetChild(parent, i); 
        if (child is T) { 
            list.Add((T)child); 
        } 
        FindChildFrameworkElementsOfType<T>(child,list); 
    } 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜