2011-11-09 73 views
2

試着理解WPF。這是我的測試類:WPF中的INotifyPropertyChanged

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    private ObservableCollection<string> _myList = new ObservableCollection<string>(); 

    public ObservableCollection<string> MyList 
    { 
     get { return _myList; } 
     set 
     { 
      _myList = value; 
      RaisePropertyChanged("_myList"); 
     } 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     comboBox1.DataContext = _myList; 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     MyList = AnotherClass.SomeMethod(); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

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

internal static class AnotherClass 
{ 
    public static ObservableCollection<string> SomeMethod() 
    { 
     return new ObservableCollection<string> {"this","is","test"}; 
    } 
} 

這是XAML

<Grid> 
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="65,51,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" /> 
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="310,51,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
</Grid> 

如何使此代碼的工作?我點擊按鈕並更新MyList後,我想要更改ComboBox數據。 PropertyChangedEventHandler始終爲空。

回答

7

問題是你直接將原始列表設置到Window.DataContext,所以沒有任何事情聽到窗口的'PropertyChanged事件。

爲了解決這個問題,設置DataContext到窗口本身:

this.DataContext = this; 

,然後改變Binding所以要參考屬性:

<ComboBox ItemsSource="{Binding MyList}" /> 

你還需要改變你的屬性定義所以它會引起屬性被更改的名稱,而不是該成員的名稱:

this.RaisePropertyChanged("MyList"); 
1

我認爲你有兩個問題:

1)結合應該是:{Binding MyList}

2)MYLIST二傳手,你應該使用RaisePropertyChanged("MyList");

相關問題