UWP中ComboBox的SelectedIndex与Enum双向绑定失效问题
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
targetTypeinConvertBackwill betypeof(MyTypeEnum)(since that's the type of the property we're binding to).Enum.Parsetakes the integer value we calculated (which aligns with your enum's underlying values: 1, 2, 3) and converts it into the actualMyTypeEnummember.- Now the binding system receives a value of the correct type, so it can successfully call the
Setmethod 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

