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!
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With