在c#和XAML中提取Key的内容值
本文关键字:Key 提取 XAML | 更新日期: 2023-09-27 18:11:22
我希望能够获得以下按钮的"Content"值,而无需为每个按钮编写函数。我有下面的函数,我想使用所有的按钮。
private void Window_KeyUp(Object sender, KeyRoutedEventArgs e)
{
SetViewModel(e.OriginalKey.ToString());
}
这是按钮的XAML代码,我希望将Content值传递给SetViewModel()函数。
<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"/>
既然您知道您的事件处理函数在每种情况下都是从Button
调用的,那么您应该能够将sender
参数转换为Button
,然后访问Content
属性。
var content = ((Button)e).Content;
Martin给了你正确的方法,我重写了你的代码:
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
}
最后两行可以这样重写:
return btn.Content;