Reaperino
Reaperino

Reputation: 145

Regroup button events in one event

I use 6 different buttons doing practically the same thing.

private void VisaCreaDoc_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
}

private void VisaTravaux_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);

}

private void VisaRemiseOuvrageIR_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVRIR);
}

private void VisaRemiseOuvrageExpl_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.REMISEOUVREXPL);
}

private void VisaMES_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.MISEENSERVICE);
}

private void VisaEncodageArchivage_Click(object sender, RoutedEventArgs e)
{
    ViewModel.ValidateItem(InfosPosteViewModel.ENCODAGEARCHIVAGE);

As you can see, they're using a function from the ViewModel with a different parameter.

Is there any way to regroup the 6 button events to have only one and kind of pass the parameter directly in the XAML call or something similar to avoid having the "code duplication" ?

Upvotes: 0

Views: 26

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

Not sure if you like it "better" but you can check which button was clicked inside the handler:

void HandleButton_Click(object sender, RoutetEventArgs e)
{
    if (sender is Button b)
    {
        if (b == VisaCreaDoc) # VisaCreaDoc is the given name of your button instace in xaml
            ViewModel.ValidateItem(InfosPosteViewModel.CREADOC);
        else if (b == VisaTravaux)
            ViewModel.ValidateItem(InfosPosteViewModel.TRAVAUX);
        else if (...) // etc.
    }
}

You can spice it up with a switch pattern matching to get rid of the if / else if / else if / ... chains.

Upvotes: 2

Rafael-WO
Rafael-WO

Reputation: 1630

Maybe you can avoid some duplicate code by creating a command for the ViewModel function (see Introduction to WPF Commands). As far as I know you can also define a CommandParameter in XAML.

Upvotes: 0

Related Questions