0

I'm trying to bind a button to a function which is in an other project (MVVM). My XML-Code (View) looks like this:

<Button Click="{Binding PressMe}">Press Me!</Button>

and my ViewModel-Code like this:

    public void PressMe()
    {
        Console.WriteLine("Ouch!");
    }

When I try to run the program the error "InvalidCastException: The Object of the type "System.Reflection.RuntimeEventInfo" couldn't be converted to the type "System.Reflection.MethodInfo". Any ideas?

Thanks for any reply

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    Click is supposed to be wired to an event handler in the code-behind file. You cannot bind to an event. You can bind to the `Command` property to a public `ICommand` source property. – mm8 Feb 05 '20 at 14:20

2 Answers2

1

if you are using MVVM as you assum, then you should use commands instead of click

<Button Command="{Binding Path=PressMe}" />

private ICommand _pressMe;

public ICommand PressMe
{
    get
    {
        if (_pressMe== null)
        {
            _pressMe= new RelayCommand(
                param => this.PressMeObject(), 
                param => this.CanPress()
            );
        }
        return _pressMe;
    }
}


private void PressMeObject()
{
    // Press me logic hier
}

private bool CanPress()
{
    // Verify command can be executed here
}
Erwin Draconis
  • 764
  • 8
  • 20
0

Click is an event so you need code behind to make it work.

While I will suggest:

  1. Replacing the "click" attribute with "Command".

  2. Implement your Relay command or other third party libraries ( Eg: MVVM Light toolkit ).

Also ICommand MVVM implementation would help.

Louis Go
  • 2,213
  • 2
  • 16
  • 29