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

时间:2009-10-22 08:45:14

标签: c# wpf xaml data-binding 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;
        }
    }
}

但是这给了我这个:

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

我需要更改什么才能使键为int且值为字符串?

3 个答案:

答案 0 :(得分:111)

到您的ComboBox添加

SelectedValuePath="Key" DisplayMemberPath="Value"

答案 1 :(得分: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" />

上面的代码很容易通过反射来概括来处理任何枚举。

希望这会有所帮助

答案 2 :(得分:0)

DevExpress 17.1.7 处理此问题的方式是设置以下属性:DisplayMemberValueMember,如果是字典,则可能是这样的:

DisplayMember="Value" 
ValueMember="Key"