2015-10-14 425 views
1

我有一個綁定到List<string>的ComboBox。當List改變時,即使PropertyChanged被引發,ComboBox也不會。在調試時,我發現List屬性甚至被讀取。當ItemsSource更改時ComboBox不會更新

可以使用下面的代碼被複制的錯誤:

XAML

<Window x:Class="ComboBoxTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="90" Width="400"> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition/> 
      <ColumnDefinition/> 
     </Grid.ColumnDefinitions> 
     <ComboBox ItemsSource="{Binding Source, Mode=OneWay}"/> 
     <Button Grid.Column="1" Content="add string" Command="{Binding}" CommandParameter="Add"/> 
    </Grid> 
</Window> 

代碼爲什麼不是組合框upda背後

using System.Windows; 

namespace ComboBoxTest 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new ViewModel(); 
     } 
    } 
} 

視圖模型

using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.ComponentModel; 
using System.Windows.Input; 

namespace ComboBoxTest 
{ 
    class ViewModel : INotifyPropertyChanged, ICommand 
    { 
     public ViewModel() 
     { 
      Source = new List<string>(); 
      Source.Add("Test1"); 
      Source.Add("Test2"); 
      Source.Add("Test3"); 
     } 

     private List<string> _Source; 

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

     private void OnPropertyChanged(string property) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(property)); 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 

     public bool CanExecute(object parameter) 
     { 
      return true; 
     } 

     public event System.EventHandler CanExecuteChanged; 

     public void Execute(object parameter) 
     { 
      if ((string)parameter == "Add") 
      { 
       Source.Add("New string"); 
       OnPropertyChanged("Source"); 
      } 
     } 
    } 
} 

婷?

回答

2

ComboBox不會更新,因爲它在檢查列表時沒有看到任何更改。引用保持不變,ComboBox不會被通知List內部的更改。

重構代碼使用ObservableCollection代替List就能解決問題,因爲ObservableCollection實現INotifyCollectionChanged,什麼是必要的告知對象內部變遷的視角。

+2

這裏重要的是它實現了'INotifyCollectionChanged',而不是'INotifyPropertyChanged'。 –

+0

我剛看到它實現了兩個,但謝謝你的提示。我會糾正它。 – Breeze

相關問題