尝试了解 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>
如何使这段代码工作?我希望单击按钮后 ComboBox 数据会发生更改并且 MyList 会更新。 PropertyChangedEventHandler 始终为 null。
问题是你直接将原始列表设置到Window.DataContext
,所以没有任何东西会听窗户的声音PropertyChanged
event.
为了解决这个问题,设置DataContext
到窗口本身:
this.DataContext = this;
然后更改Binding
所以请参考属性:
<ComboBox ItemsSource="{Binding MyList}" />
您还需要更改属性定义,以便它引发property被更改,而不是成员的姓名:
this.RaisePropertyChanged("MyList");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)