我正在尝试将nint
的原始UISegmentedControl.SelectedSegment
值绑定到我的视图模型中的enum
属性。它需要自定义值转换器,因为无法将enum
直接转换为nint
,反之亦然。
Convert
方法工作正常,因此UISegmentedControl
从视图模型中选择值。但是,当我单击控件的段时,会引发以下异常:
(MvvmCross.Converters.MvxValueConverter) Failed to ConvertBack from System.nint to MyApp.Core.ViewModels.MyViewModel+Selection with Exception: System.InvalidCastException: Specified cast is not valid.
at MvvmCross.Converters.MvxValueConverter`2[TFrom,TTo].ConvertBack (System.Object value, System.Type targetType, System.Object parameter, System.Globalization.CultureInfo culture)
在调用casts on its own方法之前似乎MvxValueConverter
virtual ConvertBack
。除了让视图模型使用const nint
值而不是单个enum
之外,我不确定解决方法是什么。
public partial class MyView : MvxTableViewController<MyViewModel>
{
// SegmentedControl is iOS UISegmentedControl in .designer.cs
public MyView() : base("MyView", null) {}
public override void ViewDidLoad()
{
base.ViewDidLoad();
var set = this.CreateBindingSet<MyView, MyViewModel>();
set.Bind(SegmentedControl).To(vm => vm.SelectedSegment).WithConversion(new SelectionValueConverter());
set.Apply();
}
public class SelectionValueConverter : MvxValueConverter<MyViewModel.Selection, nint>
{
protected override nint Convert(MyViewModel.Selection value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value; // called
}
protected override MyViewModel.Selection ConvertBack(nint value, Type targetType, object parameter, CultureInfo culture)
{
var intVal = (int)value; // never called, exception in MvxValueConverter[TFrom,TTo].ConvertBack
return (MyViewModel.Selection)intVal;
}
}
}
public class MyViewModel : MvxViewModel
{
public enum Selection
{
One = 0,
Two = 1,
Three = 2
}
Selection _selectedSegment;
public Selection SelectedSegment
{
get => _selectedSegment;
set => SetProperty(ref _selectedSegment, value);
}
public MyViewModel() {}
}
答案 0 :(得分:2)
正如您可以看到here和here MvxUISegmentedControlSelectedSegmentTargetBinding
已经从/到nint
进行转换。因此,您的转换器应该直接转到int
而不是nint
public class SelectionValueConverter : MvxValueConverter<MyViewModel.Selection, int>
{
protected override int Convert(MyViewModel.Selection value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value;
}
protected override MyViewModel.Selection ConvertBack(int value, Type targetType, object parameter, CultureInfo culture)
{
return (MyViewModel.Selection)value;
}
}
HIH