Cómo enlazar un ComboBox al diccionario genérico a través de ObjectDataProvider


Quiero llenar un cuadro combinado con datos clave/valor en el código detrás, tengo esto:

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>

Código detrás:

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;
        }
    }
}

Pero esto me da esto:

Texto alternativo http://img193.imageshack.us/img193/9218/choices.png

¿Qué tengo que cambiar para que la clave sea la int y el valor sea la cadena?

Author: Dave Clemmer, 2009-10-22

2 answers

A tu ComboBox añade

SelectedValuePath="Key" DisplayMemberPath="Value"
 103
Author: Bryan Anderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-22 15:41:57

Hay una manera más fácil.

Convierta la enumeración a Genérica.Objeto Diccionario. Por ejemplo, supongamos que desea un cuadro combinado con el día de la semana (simplemente convierta el VB a 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

En su XAML solo necesita establecer lo siguiente para enlazar a un objeto:

SelectedValue="{Binding Path= StartDayNumberOfWeeek}"  SelectedValuePath="Key" 
DisplayMemberPath="Value" />

El código anterior puede generalizarse fácilmente usando reflexión para manejar cualquier enumeración.

Espero que esto ayude

 4
Author: Jim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-27 06:03:43