2013-07-25 27 views
0

我是新來的WPF。我有一個List<string>作爲我的ListBox's ItemsSource的來源。最初,ListBox顯示我的List<string>確定中的所有Items。但是,在嘗試向我的List<string>添加一些字符串後,ListBox不會更新這些更改。我使用Binding綁定與ListBox(視圖)的數據(後面),這裏是我的代碼:列表<string>未更新回ListBox的ItemsSource?

//Code behind 
public MainWindow: Window { 
    public MainWindow(){ 
     InitializeComponent(); 
     Items = new List<string>(){"1","2","3"};//after loaded, all these values are displayed OK in my ListBox. 
     DataContext = this; 
     //Try clicking on a button to add new value 
     button1.Click += (s,e) => { 
     Items.Add("4");//But my ListBox stays the same without any update/changes. 
     }; 
    } 
    public List<string> Items {get;set;} 
} 
//XAML 
<ListBox ItemsSource={Binding Items}/> 

能否請您指出我在做什麼錯在這裏,給我一個解決方案嗎?非常感謝你提前。

+3

更改您的列表''到'的ObservableCollection '。 –

+0

@CédricBignon謝謝你,它現在有效。 – Hopeless

回答

3

如果您已經閱讀documentation of ItemsSource,您已經知道什麼是錯誤的。

[...]

這個例子顯示瞭如何創建和綁定到從ObservableCollection<T>類,它是一個集合類,提供了通知,當項目將添加或刪除派生的集合。

+0

謝謝,它現在可以工作。 – Hopeless

1

你應該嘗試的ObservableCollection,而不是因爲它是 表示一個動態數據採集,提供通知,當項目將添加,刪除,或當整個列表被刷新。

<Window x:Class="WpfApplication3.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Button Click="Button_Click" Content="Button" HorizontalAlignment="Left" Margin="441,289,0,0" VerticalAlignment="Top" Width="75"/> 
     <ListBox HorizontalAlignment="Left" ItemsSource="{Binding MyList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Name="lstbox" Height="296" Margin="21,23,0,0" VerticalAlignment="Top" Width="209"/> 

    </Grid> 
</Window> 

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

namespace WpfApplication3 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     private ObservableCollection<string> _myList = new ObservableCollection<string>(new List<string>(){"1","2","3"}); 
     int i = 3; 

     public MainWindow() 
     { 
      InitializeComponent(); 
      this.DataContext = this; 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      MyList.Add(i++.ToString()); 
     } 
     public ObservableCollection<string> MyList 
     { 
      get { return _myList; } 
      set { _myList = value; } 
     } 
    } 
}