Reputation: 37
I want to be able to get the "Content" value of the following buttons without having to write a function for each one of them. I have the following function that I want to use for all the buttons.
private void Window_KeyUp(Object sender, KeyRoutedEventArgs e)
{
SetViewModel(e.OriginalKey.ToString());
}
this is the XAML code for the button and I want the Content value to be passed to the SetViewModel() function.
<Button x:Name="btn4" Content="4" Margin="0,5,0,0" Click="btn4_Click" KeyUp ="Window_KeyUp"/>
<Button x:Name="btn5" Content="5" Margin="5,5,0,0" Click="btn5_Click" KeyUp ="Window_KeyUp"/>
<Button x:Name="btn6" Content="6" Margin="5,5,0,0" Click="btn6_Click" KeyUp ="Window_KeyUp"/>
Upvotes: 1
Views: 241
Reputation: 235
As Martin give you the right way, I rewrite your code:
private string Window_KeyUp(Object sender, KeyRoutedEventArgs)
{
Button btn = sender as Button;//get the button who rised the KeyUp event
string str = btn.Content;//get the property in a string
return str;//I replace return type from void to string in your code, this is why I return a string
}
The 2 last lines can be rewrite like this:
return btn.Content;
Upvotes: 0
Reputation: 5623
Since you know that your event handling function is called from a Button
in each case, you should be able to cast the sender
parameter to Button
an then access the Content
property.
var content = ((Button)e).Content;
Upvotes: 3