我开始学习WPF和绑定,但有一些奇怪的行为我不理解。
示例1: 一个非常简单的WPF表单,只有一个组合框(名称为C),在构造函数中包含以下代码:
public Window1()
{
InitializeComponent();
BindingClass ToBind = new BindingClass();
ToBind.MyCollection = new List<string>() { "1", "2", "3" };
this.DataContext = ToBind;
//c is the name of a combobox with the following code :
//<ComboBox Name="c" SelectedIndex="0" ItemsSource="{Binding Path=MyCollection}" />
MessageBox.Show(this.c.SelectedItem.ToString());
}
您能解释一下为什么由于c.SelectedItem为空值,这段代码会崩溃吗?
所以我想...没问题,因为它在构造函数中,让我们将代码放在Loaded表单事件中:
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BindingClass ToBind = new BindingClass();
ToBind.MyCollection = new List<string>() { "1", "2", "3" };
this.DataContext = ToBind;
MessageBox.Show(this.c.SelectedItem.ToString());
}
同样的问题,this.c.SelectedItem 为空...
备注:如果我移除 Messagebox 部分,那么绑定就正常工作了,我可以在组合框中看到值。就像需要一些时间来设置数据上下文一样。但是如何知道何时完成绑定?
感谢您的帮助。