Is there any class in C # (WPF) equivalent to Qt's QSignalMapper?

0

When I was learning C ++ / Qt I used a very interesting class that allowed me to associate several interface buttons to a single event that, by means of a value by which each button was mapped, allowed me to select the action to perform. Something like this:

...
buttonx[0] = ui->b1;
buttonx[1] = ui->b2;
buttonx[2] = ui->b3;
buttonx[3] = ui->b4;
buttonx[4] = ui->b5;
buttonx[5] = ui->b6;
buttonx[6] = ui->b7;
buttonx[7] = ui->b8;
buttonx[8] = ui->b9;

QSignalMapper *signalMapper = new QSignalMapper(this);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(botaopressionado(int)));

for(int i = 0; i < 9; i++){
    signalMapper->setMapping(buttonx[i], i + 1);
    connect(buttonx[i], SIGNAL(clicked()), signalMapper, SLOT(map()));
}

... In this way the event handler was given an integer value that, according to the mapping, indicated the button that had been pressed.

void MainWindow::botaopressionado(int m){
// O botão pressionado foi o correspondente ao valor de m
...
}

Using C # and WPF, what is the best way to get this result?

    
asked by anonymous 18.01.2017 / 16:55

1 answer

3

A simple way to do something similar would be to take advantage of the Tag property, according to MSDN:

  

Tag = Gets or sets an arbitrary object value that can be used to store custom information about this element.

public MainWindow()
{
    InitializeComponent();

     var buttons = new List<Button>();
     buttons.Add(new Button { Tag = 1 });
     buttons.Add(new Button { Tag = 2 });
     buttons.Add(new Button { Tag = 3 });

     foreach (var button in buttons)
         button.Click += Button_Click;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var valor = ((Button)sender).Tag;
    }
}

Another way, which requires more code, is to implement the Interface ICommand but then you go to the default MVVM.

private ICommand meuComando;
public MainWindow()
{
    InitializeComponent();

    var buttons = new List<Button>();
    buttons.Add(new Button { CommandParameter = 1, Command = meuComando });
    buttons.Add(new Button { CommandParameter = 2, Command = meuComando });
    buttons.Add(new Button { CommandParameter = 3, Command = meuComando });

}

About ICommand

    
18.01.2017 / 17:45