2016-03-04 80 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得到更新,这并不得到反映在您的视图查看犯规得到任何通知或事件,说明变更已到视图模型(您绑定的项目)