Question How would I 'break' out of a button press?

hex93

New member
Joined
Feb 1, 2022
Messages
1
Programming Experience
5-10
I have a WPF form with a button which links to an avent handler. Before I do anything with the event, I want to check that some conditions are met, and if not, do nothing.

I can do this via a series of if statements nested within one another, but I think my code would be much cleaner if I could just check for some conditions at the beggining, and break out of the event if those conditions are met. Is there a way to do this?

e.g. I want to do something like

C#:
private void Button_Click(object sender, RoutedEventArgs e)
{
    if (my_condition==true){break}
    
    
    //continue the code if the if statement has not broken it
    
}

Is this possible to do? I was not sure what the command was to break out of a button press, I know that you can use break for loops, so is there a similar command for events?


Thanks
 
Solution
You simply return out of the method. An event handler is just like any other method.

As a quick aside, WPF is meant to be used with the MVVM design pattern. Although, you could use WinForms style event handling, that is usually only meant for intensive view only code. If your event handlers involve business logic and/or manipulation of the data model, then you could benefit from using MVVM to keep the view code separate from the model and business logic.
You simply return out of the method. An event handler is just like any other method.

As a quick aside, WPF is meant to be used with the MVVM design pattern. Although, you could use WinForms style event handling, that is usually only meant for intensive view only code. If your event handlers involve business logic and/or manipulation of the data model, then you could benefit from using MVVM to keep the view code separate from the model and business logic.
 
Solution
Before I do anything with the event, I want to check that some conditions are met, and if not, do nothing.
With the MVVM design pattern, buttons are handled by command objects. In the command interface lets you put in logic which says "allow this button to be pressed". That sounds exactly like what you seek in the quoted text above.
 
Back
Top Bottom