2009-10-22 50 views
40

一個ComboBox通用字典結合我想,以填補在代碼鍵/值數據的組合框的背後,我有這樣的:如何通過ObjectDataProvider的

XAML:

<Window x:Class="TestCombo234.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:TestCombo234" 
    Title="Window1" Height="300" Width="300"> 
    <Window.Resources> 
     <ObjectDataProvider x:Key="Choices" ObjectType="{x:Type local:CollectionData}" MethodName="GetChoices"/> 
    </Window.Resources> 
    <StackPanel HorizontalAlignment="Left"> 
     <ComboBox ItemsSource="{Binding Source={StaticResource Choices}}"/> 
    </StackPanel> 
</Window> 

代碼背後:

using System.Windows; 
using System.Collections.Generic; 

namespace TestCombo234 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
     } 
    } 

    public static class CollectionData 
    { 
     public static Dictionary<int, string> GetChoices() 
     { 
      Dictionary<int, string> choices = new Dictionary<int, string>(); 
      choices.Add(1, "monthly"); 
      choices.Add(2, "quarterly"); 
      choices.Add(3, "biannually"); 
      choices.Add(4, "yearly"); 
      return choices; 
     } 
    } 
} 

但是這給了我這樣的:

alt text http://img193.imageshack.us/img193/9218/choices.png

我必須改變什麼,以便關鍵是int和值是字符串?

+0

谷歌揭示了這一點: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6f9ff9a9-9133-40cc-bfdb-a47d340658bf – Heinzi 2009-10-22 09:57:41

+1

看起來像上述問題中的圖片已損壞(現在[顯示廣告](http://meta.stackexchange.com/questions/263771/ban-imageshack-images-because-they-are-reusing-old-urls-for -廣告))。你可以重新上傳圖像到stack.imgur,或者編輯你的問題來刪除它嗎? – 2015-09-22 17:58:32

回答

98

要將組合框添加

SelectedValuePath="Key" DisplayMemberPath="Value" 
+2

我認爲你的意思是SelectedValuePath和DisplayMemberPath,至少對我有效,謝謝。 – 2009-10-22 15:38:07

+0

糟糕,是的,我做到了。我會解決答案。 – 2009-10-22 15:41:33

+3

你是我的英雄! – 2011-05-05 16:29:14

4

這裏有一個簡單的方法。

將枚舉轉換爲Generic.Dictionary對象。例如,讓說你想與平日的組合框(只是轉換的VB到C#)

Dim colWeekdays As New Generic.Dictionary(Of FirstDayOfWeek, String) 
    For intWeekday As FirstDayOfWeek = vbSunday To vbSaturday 
     colWeekdays.Add(intWeekday, WeekdayName(intWeekday)) 
    Next 

RadComboBox_Weekdays.ItemsSource = colWeekdays 

在XAML中,你只需要設置以下綁定到一個對象:

SelectedValue="{Binding Path= StartDayNumberOfWeeek}" SelectedValuePath="Key" 
DisplayMemberPath="Value" /> 

上面的代碼可以很容易地通過反射來處理任何枚舉。

希望這有助於