Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get XAML element by name stored in a string variable?

For example, I have an UIElement:

<TextBlock Name="sometextblock" Text="sample text"/>

In the code I have a string variable with that name:

string elementName = "sometextblock";

How to get this element, using this variable? I need to get access to element's properties, for example, i need to be able to change a Text property.

How to do this?

Thank you!

like image 475
splash27 Avatar asked Feb 27 '14 04:02

splash27


2 Answers

If you have named elements in your XAML as follows:

<TextBlock x:Name="sometextblock" />

You can find them via the FindName method:

TextBlock txt = this.FindName("sometextblock") as TextBlock;


string elementName = txt.xyzproperty //do what you want with using txt.xyz property
like image 64
Sohail Ali Avatar answered Nov 15 '22 11:11

Sohail Ali


Assuming you've this on your XAML:

<Button Name="MyButton1" .../>
<Button Name="MyButton2" .../>
<Image Name="MyImage1" .../>
<TextBox Name="MyTextBox1" .../>
<TextBox Name="MyTextBox2" .../>
<Button Name="MyButton3" .../>

You must put the name of your controls inside an array of string, so:

string[] NameControls = { "MyButton1", "MyButton2", "MyImage1", "MyTextBox1", "MyTextBox2", "MyButton3" };

Then you can iterate the controls and access the properties:

for (int i = 0; i < NameControls.Length; i++)
{
    dynamic MyControl = this.FindName(NameControls[i]);
    // do something
}

For example in my case I need to change the Opacity of determinated controls so, inside the for block I've put this:

dynamic MyControl = this.FindName(NameControls[i]);
MyControl.Opacity = 0.7;
like image 27
Marco Concas Avatar answered Nov 15 '22 11:11

Marco Concas