2012-06-04 25 views
0

我試圖將項目動態添加到組合框。添加組合框項目中的異常

但它拋出了「使用ItemsSource時操作無效,使用ItemsControl.ItemsSource訪問和修改元素」。

enter image description here

namespace Trainning 

{

public partial class ComboBox : Window 
{ 
    int intex_count; 

    public ComboBox() 
    { 
     this.InitializeComponent();   

     add_items(); 


    } 

    public List<object> add_items() 
    { 
     List<object> items = new List<object>(); 

     items.Add("chandru"); 
     items.Add(83); 

     com_add_remove.ItemsSource = items; 
     com_add_remove.SelectedIndex = 0; 

     return items; 
    } 
private void btn_add_Click(object sender, RoutedEventArgs e) 
    { 

     com_add_remove.Items.Add(txt_item.Text); 
     intex_count = com_add_remove.Items.Count; 
     com_add_remove.SelectedIndex = intex_count - 1; 

    } 
+0

你不能把源和變化同時如果你想做和做源代碼的變化,並且簡單地將源代碼更新爲像observablecollection一樣。 – JSJ

回答

2

你的問題是,當你使用ItemsSource,你也不能手動添加項目到相同分量。因此,您必須使用ItemsSouce手動添加和刪除項目。

我會去與ItemsSource,並以下變化:

取代:

com_add_remove.Items.Add(txt_item.Text); 

有:

items.Add(txt_item.Text); 

這意味着你必須添加的項目爲一類變量,而不是隻是add_items方法中的局部變量,以便您可以從btn_add_Click中引用它。

你的另一個選擇是改變add_items方法,從而增加使用ItemsSource的項目istead:

取代:

com_add_remove.ItemsSource = items; 

有:

items.ForEach(i => com_add_remove.Items.Add(i)); 
+0

非常感謝Mr.ØyvindKnobloch-Bråthen.... –

+0

樂意幫助:) –

+0

請ØyvindKnobloch-Bråthen看到這些鏈接。 .http://stackoverflow.com/questions/10880229/issue-in-creating-combobox-dynamically和http://stackoverflow.com/questions/10877616/how-to-use-on-screen-keyboard-in-whole -窗口。我在這裏發佈了一個問題。我很清楚你只有合適的人才能解決這個問題。 –

1

一旦你之後,你應該只更改數據源綁定的組合框某種數據源。

您需要在您的課程中聲明List<object> items = new List<object>();,並且只需從列表中添加和刪除項目即可。您的組合框將自動更新。

public partial class ComboBox : Window 
{ 
    int intex_count; 
    List<object> items; 
    public ComboBox() 
    { 
    this.InitializeComponent();   



    //key_value(); 

    TextBox tb = new TextBox(); 
    tb.Height = 50; 
    tb.Width = 100; 
    tb.TextAlignment = TextAlignment.Center; 
    LayoutRoot.Children.Add(tb); 
    tb.Text = "Dynamic TextBox"; 
    tb.Margin = new Thickness(0, 145, 87, 0); 
    tb.VerticalAlignment = VerticalAlignment.Top; 
    tb.HorizontalAlignment = HorizontalAlignment.Right; 
    tb.Padding = new Thickness(15, 15, 15, 15); //to center the textbox's text 

    items = new List<object>(); 
    add_items(); 
    com_add_remove.ItemsSource = items; 
    com_add_remove.SelectedIndex = 0; 
} 

public List<object> add_items() 
{ 
    //List<object> items = new List<object>(); 

    items.Add("chandru"); 
    items.Add(83);   

    return items; 
} 

private void btn_add_Click(object sender, RoutedEventArgs e) 
{ 

    items.Remove(txt_item.Text); 
    intex_count = items.Count; 

}