Is there a class in c#(WPF) equivalent to Qt’s Qsignalmapper?

Asked

Viewed 39 times

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, upon a value by which each button was mapped, allowed me to select the action to be executed. 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" received an integer value that, according to the mapping, indicated me 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 will be the best way to get this result?

1 answer

3


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

Tag = Get or Set 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 leave for the MVVM standard.

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

  • I still don’t feel brave enough to take the MVVM, but it’s on my list of "things to do ...".

  • But the first approach helps?

  • Yes of course. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.