代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何通过ObjectDataProvider将组合框绑定到通用字典

  •  44
  • Edward Tanguay  · 技术社区  · 15 年前

    我想用代码隐藏中的键/值数据填充组合框,我有:

    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 回复  |  直到 6 年前
        1
  •  108
  •   Bryan Anderson    15 年前

    添加到组合框

    SelectedValuePath="Key" DisplayMemberPath="Value"
    
        2
  •  4
  •   Ramesh Durai    12 年前

    有一种更简单的方法。

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

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

    希望这有帮助

        3
  •  0
  •   juagicre    6 年前

    DevExpress 17.1.7版 处理这些属性: DisplayMember ValueMember ,如果是字典,应该是这样的:

    DisplayMember="Value" 
    ValueMember="Key"