2011-11-09 38 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");

相关问题