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

Edw*_*uay 46 c# data-binding wpf xaml 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>
Run Code Online (Sandbox Code Playgroud)

代码背后:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我这个:

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

我需要更改什么,以便键是int,值是字符串?

Bry*_*son 112

到您的ComboBox添加

SelectedValuePath="Key" DisplayMemberPath="Value"
Run Code Online (Sandbox Code Playgroud)

  • 你是我的英雄! (3认同)
  • 另外,如果你想得到用户的选择,`SelectedValue ="{Binding myViewModelProperty}"`也很好. (3认同)
  • 我认为你的意思是SelectedValuePath和DisplayMemberPath,至少对我有用,谢谢. (2认同)

小智 5

有一个更简单的方法。

将枚举转换为 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
Run Code Online (Sandbox Code Playgroud)

在您的 XAML 中,您只需要设置以下内容即可绑定到一个对象:

SelectedValue="{Binding Path= StartDayNumberOfWeeek}"  SelectedValuePath="Key" 
DisplayMemberPath="Value" />
Run Code Online (Sandbox Code Playgroud)

上面的代码可以很容易地使用反射来泛化来处理任何枚举。

希望这可以帮助