3
I have the event Click
btnReabrirCaixa_Click
and would like to reuse the process that has within that event in a method ValidarAberturaCaixa()
, without copying and pasting the entire code, how could this be done?
3
I have the event Click
btnReabrirCaixa_Click
and would like to reuse the process that has within that event in a method ValidarAberturaCaixa()
, without copying and pasting the entire code, how could this be done?
2
Separate the contents of btnReabrirCaixa_Click
in 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, then you wouldn’t need to separate the method. I would only do that if it made sense at that point the button be automatically clicked.
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));
}
}
}
There you can use so:
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa.PerformClick();
// ...
}
Same as Windows Forms.
Another way (I find ugly and may not apply in all cases, when there is manipulation of the parameters):
private void ValidarAberturaCaixa() {
// ...
btnReabrirCaixa_Click(null, null);
// ...
}
Browser other questions tagged c#
You are not signed in. Login or sign up in order to post.
plays the button code in a method, if not using the
sender
and calls the method inside the event, and inside the other method. If you want an example, provide one that we will change it– Rovann Linhalis
ASP MVC, Web Forms? What are you working with?
– user8545
Related(duplicate ?): https://answall.com/q/215845/2541
– ramaral