2010-02-25 130 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已被提取...非常奇怪。