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

1
  • 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. Commented Feb 5, 2020 at 14:20

2 Answers 2

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

Comments

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.

Comments

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.