简体   繁体   中英

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

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM