2012-02-16 30 views
2

我是WPF的新手。我創建了一個WPF項目,並添加下面的類爲什麼ListBox不顯示綁定的ItemsSource

public class MessageList:INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string name) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 

    private List<string> list = new List<string>(); 

    public List<string> MsgList 
    { 
     get { return list; } 
     set 
     { 
      list = value; 
      OnPropertyChanged("MsgList"); 
     } 
    } 

    public void AddItem(string item) 
    { 
     this.MsgList.Add(item); 

     OnPropertyChanged("MsgList"); 
    } 
} 

然後在我添加了一個列表框和下面的主窗口是XAML內容

<Window.DataContext> 
     <ObjectDataProvider x:Name="dataSource" ObjectType="{x:Type src:MessageList}"/> 
    </Window.DataContext> 
    <Grid> 
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="52,44,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
     <ListBox Height="233" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" Margin="185,44,0,0" Name="listBox1" VerticalAlignment="Top" Width="260" ItemsSource="{Binding Path=MsgList}" /> 
    </Grid> 

這裏是MainWindow.cs的源代碼

public partial class MainWindow : Window 
    { 
     private MessageList mlist = null; 

     public MainWindow() 
     { 
      InitializeComponent(); 
      object obj = this.DataContext; 
      if (obj is ObjectDataProvider) 
      { 
       this.mlist = ((ObjectDataProvider)obj).ObjectInstance as MessageList; 
      } 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      this.mlist.AddItem(DateTime.Now.ToString()); 
     } 
    } 

我的問題是我點擊按鈕後,沒有任何內容顯示在列表框中,原因是什麼?

回答

4

你問是有原因的,而devdigital給你解決它值得一提的,爲什麼它不工作了,爲什麼他的修復功能:

你mlist勢必TH列表框和它的一切運作良好。現在,您按下按鈕,然後將條目添加到列表中。列表框不知道這個改變,因爲你的列表沒有辦法告訴「嘿,我剛剛添加了一個新的項目」。爲此,您需要使用實現INotifyCollectionChanged的Collection,如ObservableCollection。這與您的OnPropertyChanged非常相似,如果您修改MessageList上的屬性,它也會調用OnPropertychanged方法來觸發PropertyChanged事件。數據綁定註冊到PropertyChanged事件,現在知道您何時更新了屬性並自動更新UI。對於Collections,如果您想要自動更新集合上的UI,則這一點也是必需的。

2

罪魁禍首是string項目... string項目是原始類型,不要刷新綁定列表框,當你做了OnPropertyChanged

要麼使用觀察的集合或在您的button1_Click稱之爲()函數...

listBox1.Items.Refresh(); 
相關問題