0

I want to display a ListBox with around 10 items in it. Every time I update it by adding an item to a List it causes a little but noticeable delay and the UI freezes for a little while. I also tried using an ObservableCollection instead of a List as the ItemsSource, which didn't fix the problem.

My ListBox must update really fast, so I really need your help, please! :)

Here is some code:

public partial class MainPage : PhoneApplicationPage
{
    //private List<Word> Words = new List<Word>();
    ObservableCollection<Word> Words = new ObservableCollection<Word>();

    // Konstruktor
    public MainPage()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        ListBox1.ItemsSource = Words;

        for (int j = 0; j < 10; j++)
        {
            Words.Add(new Word(j.ToString()));
        }
    }
}

public class Word
{
    public String sWord { get; set; }

    public Word(String word)
    {
        this.sWord = word;
    }
}

XAML

<ListBox Name="ListBox1">
   <ListBox.ItemTemplate>
       <DataTemplate>
           <Button Content="{Binding sWord}" />
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>
Stacksatty
  • 159
  • 1
  • 10
  • show your DataTemplate / class which is being displayed in the list. If you have too many converters / logic happening, you'll have bad perf. – William Melani Jul 01 '12 at 21:25
  • I updated the post. It really isn't much code. – Stacksatty Jul 01 '12 at 21:37
  • How are you adding the items? – Matt Lacey Jul 02 '12 at 08:34
  • Just by adding an item to the list: `Words.Add(new Word("hello"));` – Stacksatty Jul 02 '12 at 12:11
  • Can you provide more code to illustrate the way you are adding items to the ObservableCollection ? To optimize your ListBox, you can create the DataTemplate in the App.xaml. – Alexis Mathieu Jul 02 '12 at 14:40
  • your actual logic looks simple, are you doing a bunch before/after you add the Word on the UI thread? – William Melani Jul 02 '12 at 14:48
  • I tried the whole thing on a fresh project. So no, I don't perform any actions before adding items to the List/ObservableCollection. I added the whole code to my first post. Can you further explain how to create the DataTemplate inside the App.xaml, please? – Stacksatty Jul 02 '12 at 16:03

1 Answers1

0

I found a solution for my problem. To fix the delay I am now using a StackPanel instead of a ListBox and add my Buttons in the following way:

StackPanel1.Children.Add(new Button()
{
    Content             = "Hello World",
    BorderBrush         = new SolidColorBrush(Colors.Transparent),
    HorizontalAlignment = HorizontalAlignment.Left
});

You can clear the StackPanel with

StackPanel1.Children.Clear();

Adding a Click event to the buttons works like this

foreach (Button btn in StackPanel1.Children)
{
    btn.Click += new RoutedEventHandler(Button_Click);
}

Very easy and much much faster!

Stacksatty
  • 159
  • 1
  • 10