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)
.