整理:WPF中Xaml中绑定枚举的写法

目的:在Combobox、ListBox中直接绑定枚举对象的方式,比如:直接绑定字体类型、所有颜色等枚举类型非常方便

一、首先用ObjectDataProvider定义资源

    <UserControl.Resources>
        <ObjectDataProvider x:Key="LeftRightAlignment" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="com:LeftRightAlignment"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <ObjectDataProvider x:Key="MenuButtonStyle" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="com:MenuButtonStyle"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>

 

1、ObjectType设置类型为枚举,GetValues是枚举的静态方法

              public static Array GetValues(Type enumType);

2、TypeName:要绑定的特定枚举类型名称

二、用ItemSource绑定静态资源

        <ComboBox ItemsSource="{Binding Source={StaticResource LeftRightAlignment}}"/>

绑定好后:可以直接用SelectValue直接绑定的选择的属性上

注意:同理、应用ObjectDataPrivder可以从代码中构造更多Xaml中应用到的资源

猜你喜欢

转载自blog.csdn.net/u010975589/article/details/83345839
今日推荐