I have a lot of buttons on a WPF window. To avoid coding the same click event over and over again I would like them to all trigger the same method and take the appropriate action based on which button I call.
I know I can cast the sender to a button and then check the name and route the code from there, but then I have to have all the names hard coded, which could be a mess if buttons get renamed a some stage.
What is a better way of doing this? Can I for example name the button from an enum? Or is it possible to get the button names for the check by actually referencing the buttons directly?
Something like this maybe?
private void btnAddTerminatorElement_Click(object sender, RoutedEventArgs e)
{
MsoAutoShapeType shapeType;
switch (((Button)sender).Name)
{
case this.btnAddTerminatorElement.Name:
shapeType = MsoAutoShapeType.msoShapeFlowchartTerminator;
break;
}
CreateChartElement(this.targetWorksheet.Shapes.AddShape(MsoAutoShapeType.msoShapeFlowchartTerminator, 100, 100, 50, 50));
}
But this doesn’t work as is because a constant is needed for the comparison…
The only good way I have come up with so far is not to use a switch statement, but to go for separate if blocks in the event function to check the caller name. Something like this:
The only method I can think of so far that is robust enough to cope with renaming the buttons. If there are any alternatives I’d be most interested in hearing about them.