MvvmCross:将nint绑定到枚举并将其转换为双向

时间:2018-06-01 17:09:27

标签: xamarin mvvmcross

我正在尝试将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() {}
}

1 个答案:

答案 0 :(得分:2)

正如您可以看到herehere 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