问题
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 string
s 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