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

57
我想在代码后台中用键/值数据填充一个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://social.msdn.microsoft.com/Forums/en-US/wpf/thread/6f9ff9a9-9133-40cc-bfdb-a47d340658bf - Heinzi
1
看起来你问题上面的图片已经损坏了(现在显示广告代替)。你能否重新上传图片到stack.imgur,或者编辑你的问题删除它? - Ilmari Karonen
3个回答

134
在你的组合框中添加:
SelectedValuePath="Key" DisplayMemberPath="Value"

3
我想你是指SelectedValuePath和DisplayMemberPath,对我来说它们有效,谢谢。 - Edward Tanguay
哎呀,是的,我会修正答案的。 - Bryan Anderson
5
另外,如果你想获取用户的选择,添加SelectedValue="{Binding myViewModelProperty}"也是不错的选择。 - yellavon

7

有更简单的方法。

将枚举转换为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" />

使用反射技术,可以轻松地将上述代码推广到处理任何枚举类型。

希望这有所帮助。


-1

DevExpress 17.1.7 的处理方式是设置这些属性:DisplayMemberValueMember,对于字典类型的数据,代码如下:

DisplayMember="Value" 
ValueMember="Key"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接