I have the event Click
btnReabrirCaixa_Click
and would like to reuse the process that has within that event in a ValidarAberturaCaixa()
method, without copying and pasting all the code, how could this be done?
I have the event Click
btnReabrirCaixa_Click
and would like to reuse the process that has within that event in a ValidarAberturaCaixa()
method, without copying and pasting all the code, how could this be done?
Separate content from btnReabrirCaixa_Click
into a method and call it in ValidarAberturaCaixa
and btnReabrirCaixa_Click
, as:
private void MetodoSeparado() {
// ...
}
private void btnReabrirCaixa_Click(object sender, EventArgs e) {
MetodoSeparado();
}
private void ValidarAberturaCaixa() {
// ...
MetodoSeparado();
// ...
}
You can trigger the click event, so you do not need to separate the method. I would only do this if it made sense at that time the button to be clicked automatically.
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa.PerformClick();
// ...
}
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
// ...
}
To be reusable and more organized, you can create an extension method in WPF:
namespace System.Windows.Controls
{
public static class ButtonExtensions
{
public static void PerformClick(this Button obj)
{
obj.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
}
}
You can use it like this:
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa.PerformClick();
// ...
}
Same as Windows Forms.
Another way (I think it's ugly and may not apply in all cases, when the parameters are manipulated):
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa_Click(null, null);
// ...
}