[英]INotifyPropertyChanged in WPF
嘗試了解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"};
}
}
這是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始終為null。
問題是你是直接將原始列表設置到Window.DataContext
,所以沒有任何東西可以監聽windows的PropertyChanged
事件。
要解決此問題,請將DataContext
設置為窗口本身:
this.DataContext = this;
然后更改Binding
所以請參閱屬性:
<ComboBox ItemsSource="{Binding MyList}" />
你還需要改變你的屬性定義,這樣它提出要更改的屬性的名稱,該成員的不是名稱:
this.RaisePropertyChanged("MyList");
我認為你有兩個問題:
1)綁定應該是: {Binding MyList}
2)在RaisePropertyChanged("MyList");
setter上你應該使用RaisePropertyChanged("MyList");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.