2016-03-04 84 views
1

概述: 我已經設置了ComoboBox綁定到List屬性。但是當我運行該應用程序時,組合框中沒有填充數據。如何解析ComboBox上的空綁定?

調試步驟:

  • 我檢查了輸出窗口綁定錯誤,告訴我說,數據源可能爲空。
  • 然後我在QueryList屬性的setter上設置一個斷點。這表明列表計數爲0.看起來在調用setter之後執行對init的調用。

我的想法是列表被調用setter後被初始化。這意味着在該階段綁定將在組合框上被調用時綁定將爲空。

問:

我怎樣才能調用init方法之前QueryList二傳手我的名單被稱爲?

代碼片段:

後面的代碼 -

//The binding property for the combo box 
    private List<string> _queryList; 
    public List<string> QueryList 
    { 
     get 
     { 
      return this._queryList; 
     } 
     set 
     { 
      this._queryList = value; 
     } 

    } 


    public MainWindow() 
    { 
     InitializeComponent(); 
     // Establish the Login control 
     Ctrl = new CrmLogin(); 
     QueryList = new List<string>(); 
     InitQueryList(); 
    } 

    //Call to init the list data 
    private void InitQueryList() 
    { 
     _queryList.Add("Query queues with unapproved email routers"); 
     _queryList.Add("Query queues with emails in pending send status"); 
    } 

組合框結合設置 -

<ComboBox HorizontalAlignment="Left" ItemsSource="{Binding QueryList}" Grid.Column="1" x:Name="queryComboBox" Grid.Row="0" VerticalAlignment="Bottom" Width="300" Visibility="Collapsed" Text="Select a query"/> 
+0

你有沒有嘗試過在構造函數的末尾調用InitializeComponent()? – Breeze

+1

嘗試使用ObservableCollection而不是列表 – Taterhead

回答

1

你忘了設置您的DataContext做:

public MainWindow() 
{ 
     InitializeComponent(); 
     this.DataContext = this; 
     // Establish the Login control 
     Ctrl = new CrmLogin(); 
     QueryList = new List<string>(); 
     InitQueryList(); 
} 
1

試試這個:

public MainWindow() 
{ 
    // Establish the Login control 
    QueryList = new List<string>(); 
    InitQueryList(); 
    InitializeComponent(); 
    Ctrl = new CrmLogin(); 
} 
+0

我試着移動InitializeComponent();按順序呼叫。但是組合框上的綁定仍然是空白的。 –

1

首先,如果你正在使用的代碼背後方法MVC那麼你就需要更新使用

comboBox1.DataSource = QueryList; 

不然,如果你使用的是標準的MVVM格式,那麼你就需要使用

INotifyPropertyChanged的

數據源

否則你將需要使用

的ObservableCollection

發生這種情況是因爲在初始化時您的_querylist的null值最初會被綁定。現在,當你querylist得到更新,這並不得到反映在您的視圖查看犯規得到任何通知或事件,說明變更已到視圖模型(您綁定的項目)