Veler
Veler

Reputation: 171

Items doesn't appear in ListBox in C#, but in XAML yes

I have a little problem with a ListBox. If I add an item by code, as it :

ListBox1.Items.Add(new MyData());
<ListBox Name="ListBox1" Height="Auto"
                    Style="{DynamicResource MyListBoxStyle}"/>

my ListBox display nothing, while Items contain the good number of item that I have add.

But if I put an item directy in my XAML and also in c#, MyData appear correctly :

ListBox1.Items.Add(new MyData());
<ListBox Name="ListBox1" Height="Auto"
                    Style="{DynamicResource MyListBoxStyle}">
                            <data:MyData/>
                        </ListBox>

Anyone know why it doesn't display correctly if I don't put an item in my XAML, and how to correct it?

Thank you in advance :)


[SOLVED] My ListBox was already shown when I adding an item. So to solve this problem, just ask to update layout to notify that ItemSource has change :

ListBox1.UpdateLayout();

Upvotes: 2

Views: 2389

Answers (1)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

I think it's because the ListBox1.Items collection does not implement the INotifyPropertyChanged/INotifyCollectionChanged. You could create an observable collection an assign it to the ItemSource.

ObservableCollection<MyData> items = new ObservableCollection()

items.Add(new MyData());

ListBox1.ItemSource = items;

The reason you don't see it added, is that the listbox is already created/filled and the collection of Items does not notify the listbox when you call the .Add method on the Items property.

Upvotes: 2

Related Questions