将UWP ComboBox ItemsSource绑定到Enum

时间:2016-08-29 15:25:42

标签: c# combobox enums uwp uwp-xaml

可以使用WPF应用程序中的ObjectDataProvider将枚举的字符串值绑定到ComboBox的ItemsSource,如this question中所示。< / p>

但是,在UWP应用程序中使用类似的代码段时,ff。显示错误消息:

&#34; Windows Universal项目不支持ObjectDataProvider。&#34;

在UWP中有一个简单的替代方法吗?

7 个答案:

答案 0 :(得分:11)

下面是我的一个原型的工作示例。

<强> ENUM

public enum GetDetails
{
    test1,
    test2,
    test3,
    test4,
    test5
}

<强>的ItemsSource

var _enumval = Enum.GetValues(typeof(GetDetails)).Cast<GetDetails>();
cmbData.ItemsSource = _enumval.ToList();

这会将组合框绑定到枚举值。

答案 1 :(得分:2)

相信我,UWP中的ComboBox和枚举不是一个好主意。节省一些时间,不要在UWP的组合框中使用枚举。花费了数小时试图使其正常运行。您可以尝试其他答案中提到的解决方案,但您将遇到的问题是,将SelectedValue绑定到枚举时,属性更改将不会触发。所以我只是将其转换为int。

您可以在VM中创建属性,并将枚举GetDetails强制转换为int。

public int Details
{
  get { return (int)Model.Details; }
  set { Model.Details = (GetDetails)value; OnPropertyChanged();}
}

然后,您只能处理带有int和string的类的列表,不确定是否可以使用KeyValuePair

public class DetailItem
{
  public int Value {get;set;}
  public string Text {get;set;}
}

public IEnumerable<DetailItem> Items
{
  get { return GetItems(); }
}

public IEnumerable<DetailItem> GetItems()
{
   yield return new DetailItem() { Text = "Test #1", Value = (int)GetDetails.test1 }; 
   yield return new DetailItem() { Text = "Test #2", Value = (int)GetDetails.test2 }; 
   yield return new DetailItem() { Text = "Test #3", Value = (int)GetDetails.test3 }; 
   // ..something like that
}

然后在Xaml上

<Combobox ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}"
 SelectedValue="{Binding Details, UpdateSourceTriggerPropertyChanged, Mode=TwoWay}"
 SelectedValuePath="Value" 
 DisplayMemberPath="Text" />

答案 2 :(得分:2)

我知道这是旧帖子,但是 将您的组合框的SelectedIndex绑定到enum属性,并定义这样的值转换器,

positioned

答案 3 :(得分:1)

如果您尝试通过xaml和Bindings设置SelectedItem,请确保先设置ItemsSource!

示例:

<ComboBox ItemsSource="{Binding ...}" SelectedItem="{Binding ...}"/>

答案 4 :(得分:0)

ComboBoxItemSource到Enum,也使用SelectedItem。并且可以选择用自定义字符串替换Enum的名称(例如翻译)。尊重MVVM模式。

枚举:

public enum ChannelMark
{
   Undefinned,Left, Right,Front, Back
}

ViewModel

private ChannelMark _ChannelMark = ChannelMark.Undefinned;

public ChannelMark ChannelMark
{
    get => _ChannelMark;
    set => Set(ref _ChannelMark, value);
}

private List<int> _ChannelMarksInts = Enum.GetValues(typeof(ChannelMark)).Cast<ChannelMark>().Cast<int>().ToList();

public List<int> ChannelMarksInts
{
    get => _ChannelMarksInts;
    set => Set(ref _ChannelMarksInts, value);
}

XAML

<ComboBox ItemsSource="{x:Bind ViewModel.ChannelMarksInts}"  SelectedItem="{x:Bind ViewModel.ChannelMark, Converter={StaticResource ChannelMarkToIntConverter}, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding  Converter={StaticResource IntToChannelMarkConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

转换器:

switch ((ChannelMark)value)
{
    case ChannelMark.Undefinned:
        return "Undefinned mark";
    case ChannelMark.Left:
        //translation
        return Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView().GetString("ChannelMarkEnumLeft");
    case ChannelMark.Right:
        return "Right Channel";
    case ChannelMark.Front:
        return "Front Channel";
    case ChannelMark.Back:
        return "Back Channel";
    default:
        throw new NotImplementedException();
}



public class IntToChannelMarkConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language) => ((ChannelMark)value).ToString();
    public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}

答案 5 :(得分:0)

这里是UWP附带的最简单,最通用的枚举绑定方法。也许这可以帮助某人,因为它易于绑定和本地化。

/// <summary>
///     Helper class to bind an Enum type as an control's ItemsSource.
/// </summary>
/// <typeparam name="T"></typeparam>
public class EnumItemsSource<T> where T : struct, IConvertible
{
    public string FullTypeString { get; set; }
    public string Name { get; set; }
    public string LocalizedName { get; set; }
    public T Value { get; set; }

    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="name"></param>
    /// <param name="value"></param>
    /// <param name="fullString"></param>
    public EnumItemsSource(string name, T value, string fullTypeString)
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("EnumItemsSource only accept Enum type.");

        Name = name;
        Value = value;
        FullTypeString = fullTypeString;

        // Retrieve localized name
        LocalizedName = AppResource.GetResource(FullTypeString.Replace('.', '-'));
    }

    /// <summary>
    ///     Create a list of EnumItemsSource from an enum type.
    /// </summary>
    /// <returns></returns>
    public static List<EnumItemsSource<T>> ToList()
    {
        // Put to lists
        var namesList = Enum.GetNames(typeof(T));
        var valuesList = Enum.GetValues(typeof(T)).Cast<T>().ToList();

        // Create EnumItemsSource list
        var enumItemsSourceList = new List<EnumItemsSource<T>>();
        for (int i = 0; i < namesList.Length; i++)
            enumItemsSourceList.Add(new EnumItemsSource<T>(namesList[i], valuesList[i], $"{typeof(T).Name}.{namesList[i]}"));

        return enumItemsSourceList;
    }
}

在ViewModel中:

    public List<EnumItemsSource<AccountType>> AccountTypes
    {
        get => EnumItemsSource<AccountType>.ToList();
    }

在视图中:

<ComboBox ItemsSource="{Binding AccountTypes}" DisplayMemberPath="LocalizedName" SelectedValuePath="Value" SelectedValue="{Binding Path=Account.Type, Mode=TwoWay}" />

答案 6 :(得分:0)

我使用 Karnaltas 答案,因为它支持使用 resx 文件轻松本地化。但是我在双向绑定和返回我的实体时遇到了麻烦。我通过更改绑定以使用 SelectedIndex 并添加转换器解决了这个问题。这样组合框就可以正确地选择初始状态并显示它。

ViewModel 与 Karnalta 的解决方案一样。

在视图中更改绑定:

<ComboBox ItemsSource="{Binding AccountTypes}" DisplayMemberPath="LocalizedName" SelectedIndex={x:Bind ViewModel.Account.Type, Mode=TwoWay, Converter={StaticResource EnumToIntConverer}" />

新转换器:

public class EnumToIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {           
        return (int)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {            
        return Enum.Parse(targetType, value.ToString());
    }
}

并且不要忘记在页面/控件中添加转换器:

<Grid.Resources>
    <ResourceDictionary>
        <converters:EnumToIntConverter x:Key="EnumToIntConverter" />
    </ResourceDictionary>
</Grid.Resources>