Search code examples
c#xamlwindows-phone-8

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!


Solution

  • 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