【问题标题】:How to bind a ComboBox to generic dictionary via ObjectDataProvider如何通过 ObjectDataProvider 将 ComboBox 绑定到通用字典
【发布时间】:2010-12-09 00:23:37
【问题描述】:

我想在后面的代码中用键/值数据填充 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;
        }
    }
}

我必须改变什么,以便键是 int,值是字符串?

【问题讨论】:

标签: c# wpf xaml data-binding combobox


【解决方案1】:

到你的组合框添加

SelectedValuePath="Key" DisplayMemberPath="Value"

【讨论】:

  • 我认为您的意思是 SelectedValuePath 和 DisplayMemberPath,它们至少对我有用,谢谢。
  • 糟糕,是的,我做到了。我会修复答案。
  • 另外,SelectedValue="{Binding myViewModelProperty}"如果想得到用户的选择,也可以加上。
【解决方案2】:

有一个更简单的方法。

将枚举转换为 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】:

    DevExpress 17.1.7 处理这个问题的方式是设置这些属性:DisplayMemberValueMember,如果是字典,它会是这样的:

    DisplayMember="Value" 
    ValueMember="Key"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 2011-05-28
      相关资源
      最近更新 更多