2012-08-22 30 views
1

在一個項目中,我展示了兩個組合框讓我們說ComboBox1和ComboBox2。我將ComboBox與KeyValue對進行綁定字典讓我們在下面給出dictionary1。如何在Silverlight中的兩個組合框中進行雙向綁定

ComboBox1.ItemsSource = dictionary1 ; 
ComboBox1.SelectedItem = ComboBox1.Items[0]; 

//Setting the Item Source of Patient Name Combo Box. 
ComboBox2.ItemsSource = dictionary1 ; 
ComboBox2.SelectedItem = ComboBox2.Items[0]; 

,並在XAML部分,我顯示如下所述在詞典的ComboBox2的CombBox1和值重點: - :如果我改變 -

<ComboBox 
     x:Name    ="ComboBox1" 
     DisplayMemberPath ="Key" 
     SelectedValue  ="{Binding Source=ComboBox2, Path=DisplayMemberPath, Mode=TwoWay}"/> 

<ComboBox 
     x:Name    ="ComboBox2" 
     DisplayMemberPath ="Value" 
     SelectionChanged ="ComboBox2_SelectionChanged" 
     /> 

目的在ComboBox1中選擇,那麼它應該會影響ComboBox2.SelectedItem的相應值,並且如果我在ComboBox2中更改了選擇,那麼它應該會影響ComboBox1.SelectedItem中的相應鍵值。

有人可以告訴我我的上述代碼中的錯誤在哪裏,或者請幫助我完成上述目標。提前致謝。

+0

你暴飲暴食有錯誤。組合框2的DisplayMemberPath包含字符串值「Value」,因此在試圖設置類似combobox1.SelectedValue = combobox1.DisplayMemberPath的東西時,這沒有意義。 – outcoldman

回答

1

這應該工作

<ComboBox 
     x:Name    ="ComboBox1" 
     DisplayMemberPath ="Key" 
     SelectedItem  ="{Binding ElementName=ComboBox2, Path=SelectedItem, Mode=TwoWay}"/> 

<ComboBox 
     x:Name    ="ComboBox2" 
     DisplayMemberPath ="Value" 
     /> 
+0

感謝Outcoldman它爲我工作:) – SharpUrBrain

+0

dbaseman,我認爲應該有Mode = TwoWay,否則它不適合我。謝謝所有的快速回答 – SharpUrBrain

+1

dbaseman,在SL中默認模式有OneWay綁定,不像在WPF TwoWay中。 – outcoldman

1

我可以看到至少有兩個問題:

  1. 有待的ElementName而不是來源
  2. 應該是路徑代替DisplayMemberPath

我認爲這應該工作:

<ComboBox 
    x:Name    ="ComboBox1" 
    DisplayMemberPath ="Key" 
    SelectedValue  ="{Binding ElementName=ComboBox2, Path=SelectedValue}"/> 

<ComboBox 
    x:Name    ="ComboBox2" 
    DisplayMemberPath ="Value" /> 
相關問題