【发布时间】:2023-03-27 16:40:01
【问题描述】:
所以我有 ComboBox 和一些项目,它的 SelectedIndex 绑定 TwoWay 与 MyTypeEnum 类型的属性这个想法是它的选定索引值可以由 enum to 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
//使用 byte 作为父级,这样我就可以从 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;
}
【问题讨论】:
标签: c# xaml uwp combobox ivalueconverter