WPF Combobox绑定到DataTable无法正常工作

时间:2013-05-21 12:55:27

标签: wpf data-binding combobox

ComboBox定义为

<ComboBox Name="cmbCallSource" />

在表单加载时,我运行此代码(我检查了dtSources数据表在调试器中以适当的内容结束):

//Init Source List
        dtSources = new DataTable();
        dtSources.Columns.Add(new DataColumn("Key", Type.GetType("System.Int32")));
        dtSources.Columns.Add(new DataColumn("Caption", Type.GetType("System.String")));
        dtSources.Rows.Add(new object[] { -1, Utility.GetStringByKey("string1") }); ;
        dtSources.Rows.Add(new object[] { 0, Utility.GetStringByKey("string2") }); ;
        dtSources.Rows.Add(new object[] { 1, Utility.GetStringByKey("string3") }); ;
        dtSources.Rows.Add(new object[] { 2, Utility.GetStringByKey("string4") }); ;
        dtSources.Rows.Add(new object[] { 3, Utility.GetStringByKey("string5") }); ;
        dtSources.Rows.Add(new object[] { 4, Utility.GetStringByKey("string6") }); ;

        //Attempt 1
        cmbCallSource.DataContext = dtSources.DefaultView;
        cmbCallSource.SelectedValuePath = "Key";
        cmbCallSource.DisplayMemberPath = "Caption";

        //Attempt 2
        //Binding myBinding = new Binding("Name");
        //myBinding.Source = dtSources; // data source from your example

        //cmbCallSource.DisplayMemberPath = "Caption";
        //cmbCallSource.SelectedValuePath = "Key";
        //cmbCallSource.SetBinding(ComboBox.ItemsSourceProperty, myBinding); 

我尝试了两种方式(第二种方式被注释掉了)。无论如何,Combobox最终都是空的。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

设置Itemsource属性,而不是DataContext

cmbCallSource.ItemsSource = dtSources.DefaultView;