2010-02-25 127 views
3

我开始使用WPF和绑定,但有一些奇怪的行为,我不明白。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为NULL。

所以我虽然...没有问题,这是因为它在构造函数中,我们把代码中加载的窗体事件:

 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的东西,那么绑定工作正常,我有组合框中的值。这就好像在datacontext设置后需要“一些”时间。但是如何知道绑定何时完成?

发送你的帮助。

回答

2

这是因为selectionchanged还没有触发,所以selecteditem仍然为空。

private void c_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    MessageBox.Show(this.c.SelectedItem.ToString()); 
} 

如果你是WPF的新手,我建议你去看看MVVM模式。有一个非常好的介绍视频在这里:http://blog.lab49.com/archives/2650

+0

地狱,事实上,它甚至不仅仅是选定的项目,它是空的。组合框的反应就好像它根本没有绑定一样(项目也是空的)。 很好奇,因为这是silverlight 3 – Fabian 2010-02-25 19:45:51

+0

是的,没有打扰检查:P。 有点奇怪,它在silverlight中工作,但不是在wpf中。也许他们有不同的加载控制方式。 我检查了OnContentRendered并且在它呈现控件本身之前已经设置了MyCollection。 我没有时间atm看更多的东西,但红色的大门.net反射器是一个很好的工具,看看.net框架中发生了什么。帮助我发现了WPF的很多奇怪的事情。 对不起,错误的答案,但我希望你看看MVVM作为一个非常好的模式来开发WPF应用程序。 – Michael 2010-02-25 20:07:50

+0

Tx你迈克尔,我将项目形式silverlight 3移动到WPF,乍一看似乎很容易,但他们之间真的很奇怪的差异,使得事情变得相当复杂! :) – Fabian 2010-02-25 21:41:07

0

您的绑定发生在Window_Loaded事件中,但它没有绘制到scren,所以没有SelectedItem。

你将不得不听听你的Binding或DataContext的PropertyChanged事件。然后OnPropertyChanged,调出你的信息箱

0

的Tx的评论,它应该是这样的,我试试这个,这是工作:

BindingClass ToBind = new BindingClass(); 
    public Window1() 
    { 
     InitializeComponent(); 
     ToBind.MyCollection = new List<string>() { "1", "2", "3" }; 

     this.DataContext = ToBind; 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show(this.c.SelectedItem.ToString()); 
    } 

所以在这里,即使是不在屏幕上绘制selecteditem已被提取...非常奇怪。