I am working on a C# WPF project. I have multiple buttons that I want to essentially do the same thing, but post the results back into different textboxes. Similar to the xaml snippet below:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBox x:Name="ATextbox"/>
<TextBox x:Name="BTextbox"/>
<TextBox x:Name="CTextbox"/>
</StackPanel>
<StackPanel Grid.Column="1">
<Button x:Name="AButton" Click="Button_Click" Content="Foo" Grid.Column="1"/>
<Button x:Name="BButton" Click="Button_Click" Content="Foo" Grid.Column="1"/>
<Button x:Name="CButton" Click="Button_Click" Content="Foo" Grid.Column="1"/>
</StackPanel>
</Grid>
As you can see, I would really like to have a single "click" method to handle all three buttons. I would like the C# to look something like the following:
private void Button_Click(object sender, EventArgs e)
{
//Get the name of the button clicked
DependencyObject dpsender = sender as DependencyObject;
string name = dpsender.GetValue(FrameworkElement.NameProperty) as string;
string subName = name.Substring(0, 1);
string tbName = subName + "Textbox";
string text = "Calculated text";
tbName.Text = text;
}
I essentially get the name of the button clicked, grab the prefix (A, B, or C), then concatenate the prefix and "Textbox" to get the name of textbox I am wanting put the data in.
The last line obviously doesn't work, because tbName is a string, which does not have a "Text" property. However, I know that at runtime the name of a Textbox object will be contained in the tbName variable. Is there any way to achieve what I am trying to do? I know I could obviously create separate methods for each button, but I would rather avoid this if possible.
Thanks