如何通过ObjectDataProvider将ComboBox绑定到通用字典

我想用代码中的键/值数据填充ComboBox,我有这样的:

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; } } } 

但是这给了我这个:

替代文字http://img193.imageshack.us/img193/9218/choices.png

我有什么要改变,所以关键是int和值是string?

给你的ComboBox添加

 SelectedValuePath="Key" DisplayMemberPath="Value" 

有一个更简单的方法。

将枚举转换为Generic.Dictionary对象。 例如,假设你想要一个带星期几的combobox(只需将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" /> 

上面的代码可以很容易地通过reflection来处理任何枚举。

希望这可以帮助