[英]How can i find a specific element/field in the class
I have 2 page app. 我有2页应用程序。 First page MainPage, and second page is class and name "Links".
第一页是MainPage,第二页是类和名称“链接”。 I have buttons in mainpage.
我在主页上有按钮。 and i have string variables in "Links" with the same name as the buttons.
我在“链接”中具有与按钮同名的字符串变量。 For example
例如
class Links
{
public static string a1 = "data1";
public static string a2 = "data2";
public static string a3 = "data3";
}
//Main page
public partial class MainPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void allclickevents(object sender, RoutedEventArgs e)
{
Button x = (Button)sender;
string findthisname=x.Content.ToString();
//I need to find the string data of the same name in "Links" class. And show messagebox, for ex if button a2 messagebox shows "data2".
}
}
Design Page(Xaml page): 设计页面(Xaml页面):
<Button x:Name="a1" Content="a1" HorizontalAlignment="Left" Margin="260,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>
<Button x:Name="a2" Content="a2" HorizontalAlignment="Left" Margin="360,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>
<Button x:Name="a3" Content="a3" HorizontalAlignment="Left" Margin="460,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>
All buttons click events set to allclickevents
method, and i am use (Button). 所有按钮的单击事件都设置为
allclickevents
方法,并且我正在使用(按钮)。 sender and find specific button name. 发送者并找到特定的按钮名称。 Need only find same named string data in Links class.
只需要在Links类中找到相同的命名字符串数据。 I need to find the string data of the same name in "Links" class.
我需要在“链接”类中找到同名的字符串数据。 And show messagebox, for ex if button a2 messagebox shows
data2
. 然后显示messagebox,例如,如果按钮a2 messagebox显示
data2
。 Please help. 请帮忙。
The only way to do this is via reflection, which is a pretty good indicator that its not the right approach to solving the overall problem. 做到这一点的唯一方法是通过反思,这是一个很好的指标,表明它不是解决整体问题的正确方法。
That being said, the following code will do it: 话虽如此,下面的代码可以做到这一点:
string data = (string) typeof(Links).GetField(findthisname).GetValue(null);
See MSDN for GetField
and SO for how to use it to access static members. 有关如何使用它访问静态成员的信息,请参见MSDN中的
GetField
和SO 。
To get the message box, just use MessageBox.Show(data)
. 要获取消息框,只需使用
MessageBox.Show(data)
。
FieldInfo f_key = typeof(Links).GetField(p);
var o = f_key.GetValue(null);
these code should work, but if you use Dictionary,it will be much easier,like this: 这些代码应该可以工作,但是如果您使用Dictionary,它将变得更加容易,例如:
Dictionary<String,String> links = new Dictionary<string, string>();
links.Add("a1","data1");
links.Add("a2", "data2");
links.Add("a3", "data3");
when you use it : 使用时:
links["ai"]
will return "datai"
links["ai"]
将返回"datai"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.