2012-07-01 22 views
0

我想顯示一個列表框,其中包含大約10個項目。每次我通過將項目添加到List進行更新時,它會導致一些但明顯的延遲,並且UI會凍結一段時間。我也嘗試使用ObservableCollection而不是List作爲ItemsSource,這並沒有解決問題。正在更新列表框導致延遲

我的列表框必須更新得非常快,所以我真的需要你的幫助,請! :)

下面是一些代碼:

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> 
+0

顯示正在列表中顯示的DataTemplate /類。如果你有太多的轉換器/邏輯發生,你會有不良的表現。 –

+0

我更新了帖子。它確實不是太多的代碼。 – Stacksatty

+0

你如何添加項目? –

回答

0

,我發現我的問題的解決方案。與

StackPanel1.Children.Clear(); 

添加Click事件的按鈕

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

您可以清除的StackPanel:要解決我現在用一個StackPanel的延遲,而不是一個列表框,並添加我的按鈕按以下方式這樣的作品

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

非常簡單,快得多!