将TabControl绑定到枚举 [英] Binding TabControl to an enum

查看:83
本文介绍了将TabControl绑定到枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了一个枚举成员(无)外,我需要在TabControl上将所有枚举值显示为选项卡项

I need to display all enum values as tab items on TabControl, except one enum member (None)

enum MyEnum { Value1, Value2, Value3, None }

TabControl应该显示三个选项卡(Value1,Value2和Value3)。我需要能够通过绑定到SelectedItem属性来获取/设置ViewModel中的当前选项卡。每个选项卡的标题都使用本地化的枚举值,目前我使用转换器。

TabControl should display three tabs (Value1, Value2 and Value3). I need to be able to get/set current tab in the ViewModel by binding to SelectedItem property. Header for each tab uses localized enum value, which currently I do using converter.

这可能吗?我已经尝试了很多方法,但是无法使其正常工作。手动添加每个TabItem没什么麻烦,但是我不确定如何使SelectedItem(标签)成为枚举类型。

Is this possible? I have tried many things, but could not make it work. I have no trouble with manually adding each TabItem, but I am unsure how to make SelectedItem (tab) to be of enum type.

推荐答案

<我找到了解决方案。通常,您这样做是为了获得枚举成员的列表:

I found the solution. Normally you would do this in order to get a list of enum members:

<ObjectDataProvider x:Key="SomeEnumValues"
                    MethodName="GetValues" 
                    ObjectType="{x:Type sys:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="vm:SomeEnum" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

这样可以得到所有成员,所以这不是走的路。我创建了一个自定义转换器,该转换器将接受枚举值,并在转换方法$ b中从类型

This would get all the members, so its not a way to go. I have created a custom converter that will accept enum value, and extract all members from type

// in the convert method
Type type = value.GetType();

List<object> enumValues = new List<object>();

// add each member, except None (has value of 0)
foreach (var field in type.GetFields())
{
    if (field.IsLiteral)
    {
        var x = field.GetValue(null);

        // add new value
        if ((int)x != 0)
            enumValues.Add(field.GetValue(null));
    }
}

本地化是在ItemTemplate中完成的。在这里,我还使用转换器(不同的转换器),在其中获得本地化的值。

Localization is done in the ItemTemplate. In there I also use converter (different one), where I get the localized value.

<DataTemplate x:Key="EnumItemTemplate">
    <TextBlock Text="{Binding Mode=OneWay, Converter={StaticResource enumConverter}}"/>
</DataTemplate>

这篇关于将TabControl绑定到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆