简体   繁体   中英

How can i find a specific element/field in the class

I have 2 page app. First page MainPage, and second page is class and name "Links". 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):

<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). sender and find specific button name. Need only find same named string data in Links class. 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 . 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.

To get the message box, just use 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<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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM