MVVCross: Pass an enum value as a CommandParameter for Android

孤者浪人 提交于 2019-12-08 05:00:59

问题


I want to pass an enum value as a CommandParameter. My enum is defined as:

public enum MyEnum
{
   One,
   Two
}

And in my axml I have:

local:MvxBind="Click MyCommand, CommandParameter=MyEnum.One"
...
local:MvxBind="Click MyCommand, CommandParameter=MyEnum.Two"

and MyCommand is defined in my ViewModel as

public IMvxCommand MyCommand
{
  get { return new MvxCommand<MyEnum>(myfunction); }
}

private void myfunction(MyEnum p_enumParam)
{
  switch (p_enumParam)
  {
      case MyEnum.One:
          doSomething1();
          break;
      case MyEnum.Two:
          doSomething2();
          break;
  }
}

When I run it, I get the error "System.InvalidCastException: Cannot cast from source type to destination type."

Obviously, because it cannot cast MyEnum.One and MyEnum.Two to the MyEnum type. So how can I convince it that MyEnum.One and MyEnum.Two are of MyEnum type?

Thanks, Pap


回答1:


MvvmCross can't guess the type of enum from the binding statement - so it can't perform this binding.

The easiest route on this is probably to workaround this using strings instead - and you will then need to use Enum.Parse from the string to the enum in your ViewModel.


An alternative is that you could also implement an enum parsing ValueConverter which just parsed the string - e.g. you could base on https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding/ValueConverters/MvxCommandParameterValueConverter.cs - you could add Enum.Parse to this to create:

public class MyEnumCommandValueConverter
    : MvxValueConverter<ICommand, ICommand>
{
    protected override ICommand Convert(ICommand value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return new MvxWrappingCommand(value, Enum.Parse(typeof(MyEnum), parameter.ToString()));
    }
}

You could then bind using nesting - using something like:

local:MvxBind="Click MyEnumCommand(MyCommand, 'Two')"


来源:https://stackoverflow.com/questions/25149547/mvvcross-pass-an-enum-value-as-a-commandparameter-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!