2

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 Answer 1

3

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')"
Sign up to request clarification or add additional context in comments.

3 Comments

I did it using ints and then converting them into their corresponding enum value, but I like your idea better...Thanx
Any chance of adding this feature in the future?-> The ability to pass enums as CommandParameters?
Happy to accept pull requests and fearure requests - but I think it will be hard to implement because when you construct the binding, it is too early to look at the type of enum that the vm wants. However, developers can be very resourceful - so maybe there is a way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.