sht*_*kuh 4 c# data-binding wpf inotifypropertychanged
尝试了解WPF.这是我的测试类:
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"};
}
}
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
如何使这段代码工作?我希望在单击按钮并更新MyList后,ComboBox数据将被更改.PropertyChangedEventHandler始终为null.
问题是你直接将原始列表设置为Window.DataContext
,所以没有任何东西听过窗口的PropertyChanged
事件.
要解决此问题,请将DataContext
窗口设置为:
this.DataContext = this;
Run Code Online (Sandbox Code Playgroud)
然后改变Binding
所以参考属性:
<ComboBox ItemsSource="{Binding MyList}" />
Run Code Online (Sandbox Code Playgroud)
你还需要改变你的属性定义,使其提高了的名称属性被更改,该成员的不是名称:
this.RaisePropertyChanged("MyList");
Run Code Online (Sandbox Code Playgroud)