将UWP组合框将源绑定到枚举

问题描述 投票:9回答:3

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

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

“ Windows Universal项目不支持ObjectDataProvider。”

在UWP中是否有简单的替代方法可以做到这一点?

c# combobox enums uwp uwp-xaml
3个回答
2
投票
示例:

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


0
投票
枚举:

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

© www.soinside.com 2019 - 2024. All rights reserved.