uwp selectedIndex 与枚举的绑定无法双向工作

uwp selectedIndex binding with enum not working twoway

所以我有 ComboBox 和一些项目,它的 SelectedIndex 绑定了 TwoWay 属性 类型 MyTypeEnum 这个想法是它选择的索引值可以通过 enum 到 int 转换器设置,当用户更改选择时组合框本身然后新的 selectedIndex 应该更新它绑定到的值。它工作正常 OneWay 即:从 属性 到 SelectedIndex,但不工作 reverse 所以有了断点我已经确认 Set 当我更改组合框的选择时,我的绑定 属性 方法不会执行,但是我的转换器的 ConvertBack 方法会执行,就像它应该的那样.

我准备了一个最小且简单的代码库来重现该问题:https://github.com/touseefbsb/ComboBoxToEnumBug

代码

MainPage.xaml

<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
    <local:IdToIndexConverter x:Key="IdToIndexConverter"/>
</Page.Resources>
<Grid x:DefaultBindMode="TwoWay">
    <ComboBox SelectedIndex="{x:Bind ViewModel.MyTypeEnum, Converter={StaticResource IdToIndexConverter}}" >
        <ComboBoxItem>item 1</ComboBoxItem>
        <ComboBoxItem>item 2</ComboBoxItem>
        <ComboBoxItem>item 3</ComboBoxItem>
    </ComboBox>
</Grid>

MainViewModel

public class MainViewModel : Observable
{
    private MyTypeEnum _myTypeEnum = MyTypeEnum.Type1;

    public MyTypeEnum MyTypeEnum
    {
        get => _myTypeEnum;
        set => Set(ref _myTypeEnum, value);
    }
}

可观察

public class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

MyTypeEnum

//使用字节作为父节点,这样我就可以从 1 而不是 0 开始计数

public enum MyTypeEnum : byte
{
    Type1 = 1,
    Type2,
    Type3
}

转换器

public class IdToIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language) => System.Convert.ToInt32(value) - 1;

    public object ConvertBack(object value, Type targetType, object parameter, string language) => ((int)value) + 1;
}

I have confirmed that Set method of my bound property does not execute when I change selection of combobox however the ConvertBack method of my converter does execute which is like it should.

您的 ConvertBack 方法 return 是 int,但它应该 return 是 MyTypeEnum

视图模型的来源 属性 不能设置为 int,只能设置为 MyTypeEnum

Cast int to enum in C#