将DataGridComboBox绑定到枚举

时间:2014-03-11 16:20:02

标签: c# wpf

我目前正在将我的Datagrid绑定到DTO。除了枚举之外,它还能够提取值。当进入的值与枚举不完全相同时,如何绑定枚举。

public enum Channels { Phone, Website, Email, Skype, Cell, Fax }

Channel的可能值介于0-5之间

<DataGrid ItemsSource={Binding ContactMethods} >
    <DataGridComboBoxColumn  
         Header="Type" 
         SelectedItemBinding="{Binding Channel, Mode=TwoWay}" 
         shell:EnumHelper.Enum="{x:Type clients:ContactMethods+Channels}" 
         DisplayMemberPath="Channel"/>

2 个答案:

答案 0 :(得分:2)

要获取XAML中enum的所有值,您可以使用ObjectDataProvider之类的内容:

<ObjectDataProvider x:Key="MyEnumDataProvider" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="NameSpaceOfMyEnum:MyEnum"/>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

要显示enum - 值,例如ComboBox(我使用此处),您必须:

ItemsSource="{Binding Source={StaticResource MyEnumDataProvider}}"

我创建了一个新窗口并在Window.Resources中添加了ObjectDataProvider。 xaml是:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="100" Width="250">
    <Window.Resources>
        <ObjectDataProvider x:Key="MyEnumDataProvider" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="wpfApplication1:MyEnum"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <ComboBox ItemsSource="{Binding Source={StaticResource MyEnumDataProvider}}"></ComboBox>
</Window>

enum只是

enum MyEnum
{
    EnumValue1,
    EnumValue2,
    EnumValue3,
}

如果添加

,我认为评论中的xaml有效
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"

到窗口的命名空间。必须修改wpfApplication1以匹配枚举

的命名空间

答案 1 :(得分:0)

public enum Channels { Phone, Website, Email, Skype, Cell, Fax }
var ChannelsForBind = Enum.GetValues(typeof(Channels)).Cast<Channels>();