You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP中ComboBox的SelectedIndex与Enum双向绑定失效问题

Fixing Two-Way Binding Issue Between ComboBox SelectedIndex and Enum in UWP

Let's break down why your reverse binding isn't working, even though the ConvertBack method is firing:

The core problem lies in your IdToIndexConverter's ConvertBack method. Right now, you're returning an int value (((int)value) + 1), but your bound property MyTypeEnum is of type MyTypeEnum—an enumeration. The UWP binding system can't implicitly convert this integer to your enum type, so it can't set the value on your view model property, which is why your Set method never gets called.

The Fix

Update your ConvertBack method to convert the calculated integer into the corresponding MyTypeEnum value. Here's the corrected converter code:

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

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    {
        // Convert the SelectedIndex (int) to the matching enum value
        int enumUnderlyingValue = ((int)value) + 1;
        return Enum.Parse(targetType, enumUnderlyingValue.ToString());
    }
}

Why This Works

  • targetType in ConvertBack will be typeof(MyTypeEnum) (since that's the type of the property we're binding to).
  • Enum.Parse takes the integer value we calculated (which aligns with your enum's underlying values: 1, 2, 3) and converts it into the actual MyTypeEnum member.
  • Now the binding system receives a value of the correct type, so it can successfully call the Set method on your view model property.

Additional Confirmation

While your parent Grid has x:DefaultBindMode="TwoWay", it's still good practice to explicitly declare the binding mode on the ComboBox to avoid any ambiguity:

<ComboBox SelectedIndex="{x:Bind ViewModel.MyTypeEnum, Converter={StaticResource IdToIndexConverter}, Mode=TwoWay}" >

内容的提问来源于stack exchange,提问作者Muhammad Touseef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:21:49