添加项目到组合框元素

问题描述:

我绑定了一个数据表组合框,就像我在下面的代码中显示的那样。添加项目到组合框元素

 objComboBox.ItemsSource = objDataTableNew.DefaultView; 
     objComboBox.DisplayMemberPath = objDataTableNew.Columns[0].ToString(); 
     objComboBox.SelectedValuePath = objDataTableNew.Columns[1].ToString(); 
     objComboBox.SelectedIndex = 0; 

现在我想显示文本为“选择”和值“-1”增加组合框项目列表的顶部。 直接我不能添加,因为itemsource与数据表绑定。 我试图在索引零处插入一行到objDataTableNew。但我有一个概率。从DB获得的数据表的第0列是整数列。所以我不能插入字符串值“选择”到该列。

我该如何做到这一点?

+0

我猜[讨论] [1] shoudl给你你需要的所有信息。 [1]:http://*.com/questions/199642/how-to-insert-empty-field-in-combobox-bound-to-datatable – Marthin 2011-12-28 11:29:42

+0

好一个@Marthin,浇铸YHE条目并插入位置0.many谢谢 – 2011-12-28 11:55:17

  List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(objDataTable.Rows.Cast<DataRow>().Select(row => new KeyValuePair<string, string>(row[DisplayMemberColumn].ToString(), row[SelectedValueColumn].ToString()))); 
      list.Insert(0, new KeyValuePair<string, string>("<--Select-->", "-1")); 
      objComboBox.ItemsSource = list; 
      objComboBox.DisplayMemberPath = "Key"; 
      objComboBox.SelectedValuePath = "Value"; 
      objComboBox.SelectedIndex = 0; 

将objComboBox.ItemsSource与ObservableCollection绑定,其中collection的内容将是“select”字符串+数据表项。

尝试使用WPF中的CompositeCollection

<ListBox xmlns:System="clr-namespace:System;assembly=mscorlib" 
    xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib"> 
     <ListBox.Resources> 
      <Collections:ArrayList x:Key="TestCollection"> 
       <System:String>1</System:String> 
       <System:String>2</System:String> 
       <System:String>3</System:String> 
       <System:String>4</System:String> 
      </Collections:ArrayList> 
     </ListBox.Resources> 
     <ListBox.ItemsSource> 
      <CompositeCollection> 
       <System:String>--Select--</System:String> 
       <CollectionContainer 
        Collection="{StaticResource TestCollection}"/> 
      </CompositeCollection> 
     </ListBox.ItemsSource> 
    </ListBox> 

所以代替StaticResource您可以从您的视图模型提供Binding为好。

希望这会有所帮助。

所有数据绑定到数据表中,并创建新行的DataTable

DataRow row = dt.NewRow(); row["Category"] = "<-Please select Category->"; dt.Rows.InsertAt(row, 0); CBParent.DataSource = dt; 
+0

正确地阅读问题。我不能像这样插入,因为它是整数列。 – 2011-12-28 12:43:12

+0

@NitheshKumarKuntady正确阅读你自己的问题。您将收到一条错误消息,指出您无法在整数列中插入字符串。错误消息是非常明显的。 – Paparazzi 2011-12-28 16:16:36

错误消息首先是非常自我解释。看来你正在绑定一个字符串(“选择”)在一个整数列[0]。在[0](整数列)中插入整数“-1”,在[1]中插入字符串“select”(字符串列)。假设[1]是一个字符串列。

这为我工作:

DataRow row = dt.NewRow(); 
row["Category"] = "<-Please select Category->"; 
dt.Rows.InsertAt(row, 0); 
CBParent.DataSource = dt;