I want to be able to refer to a WPF element in C# via the text in a string. Something like this:
SelectElementFromString("TestButton").Opacity = 1;
Can I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Do you really need to? Somehow I doubt it. How about:
XAML:
Code:
Using strings in that manner is almost always a bad idea and serves only to make your code fragile (I say almost because there are some valid reasons, they are just not common). Also, why does your method return a string?
EDIT: Based on your comment here I would suggest that you simply use a collection to iterate through your controls:
Almost every beginner programmer wants to do this (including myself some number of years ago). Create a bunch of controls named something like
label0,label1,label2, etc. and then access them in a loop like this:This is bad for various reasons and (luckily) completely unnecessary. Load all of your controls into a
List<T>and iterate through them as needed.As noted by H.B., my answer helps the OP, but may not help future people searching this forum who actually need a direct answer. So, here is a repost of Jon’s answer (thanks, would throw you some more rep if I could =D)
Note: If you use x:Name, the control will also be available as a field on the codebehind for your FrameworkElement, and you will be able to access it directly.