2012-10-04 31 views
0

我有一個字典,我想允許在組合框中選擇鍵,但也可以顯示值而不必創建另一列。在組合框中顯示詞典[鍵,值]但在選擇後只有[鍵]

舉例來說,如果我的字典裏包括3個項目,現在

Dictionary<string, double> test = new Dictionary<string, double>(); 
    //KEY , VALUE 
    //"Item1" , 4.0 
    //"Item2" , 4.5 
    //"Item3" , 5.0 

我想要的組合框下拉列表中顯示可用的選項顯示key和值

[Item1, 4.0] 
[Item2, 4.5] 
[Item3, 5.0] 

,並說,如果[Item2, 4.5]被選中,那麼只有該鍵被顯示在組合框中作爲當前選擇,在這種情況下,將在選擇之後顯示以下內容...

Item2

我試過以下,但是這表明[key,value]同時在組合框中選擇列表和選擇

comboboxColumn2.SelectedValuePath= "Key"; 
comboboxColumn2.ItemsSource = test; 

後,我一直在使用的組合與comboboxColumn2.DisplayMemberPath= "Value";也試過,但不能把它格式化,因爲我想。

任何人都可以說如果可能的話和正確的語法是什麼?

編輯:

組合框實際上ComboboxColumns所以只有2個可用的事件,如果你想這樣做的代碼不出現非常有用

<DataGrid.Columns> 
    <DataGridComboBoxColumn Header="Department Id" x:Name="comboboxColumn1" 
      SelectedValueBinding="{Binding Department Id}" /> 
    <DataGridComboBoxColumn Header="Department Id" x:Name="comboboxColumn2" 
     SelectedValueBinding="{Binding Department Name}"/> 
</DataGrid.Columns> 

回答

2

此背後卻是:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="168,100,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" DropDownOpened="comboBox1_DropDownOpened" DropDownClosed="comboBox1_DropDownClosed" /> 

public MainPage() 
    { 
     InitializeComponent(); 
     var source = new Dictionary<string, double>(); 
     source.Add("Item1", 0.4); 
     source.Add("Item2", 0.3); 
     source.Add("Item3", 0.1); 

     var formateDSource = new Dictionary<string, string>(); 

     foreach (var item in source) 
     { 
      formateDSource.Add(string.Format("[{0}, {1}]", item.Key, item.Value), item.Key); 
     } 

     comboBox1.ItemsSource = formateDSource; 
     comboBox1.DisplayMemberPath = "Value"; 
    } 

    private void comboBox1_DropDownOpened(object sender, EventArgs e) 
    { 
     comboBox1.DisplayMemberPath = "Key"; 
    } 

    private void comboBox1_DropDownClosed(object sender, EventArgs e) 
    { 
     comboBox1.DisplayMemberPath = "Value"; 
    } 

我剛剛創建了一個formatedSource,然後根據您的描述更改了displayMemberPath。

希望它有幫助

相關問題