Home > Net >  How to switch a button click event sender from code behind to MVVM?
How to switch a button click event sender from code behind to MVVM?

Time:03-01

I have a button with its Click event on the code-behind, something like this:

private void ButtonManager_OnClick(object sender, RoutedEventArgs e)

    {
        var addButton = sender as FrameworkElement;
    }

In case I move to MVVM and no code-behind, I use a Command class with Execute, something like this:

public override void Execute(object? parameter)
    {
      // sender?
    }

How should I manage the "sender as.." that was used in code-behind?

CodePudding user response:

You can use CommandParameter to bind the control to itself. but it's not a good idea to send the ViewComponent to ViewModel and change it. because in MVVM, the View shouldn't know anything about View. If you want to change anything in View, you can define properties in ViewModel and bind them to view separately. Any way, the solution for your question is in the code below but I don't suggest it:

Sample Code

Xaml:

<Button Command="{Binding Command}" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=.}"/>

ViewModel:

private void Execute(object? obj)
{
   var sender = obj as FrameworkElement;
}
  • Related