如何通过存储在字符串变量中的名称获取XAML元素?

spl*_*h27 2 c# xaml windows-phone-8

例如,我有一个UIElement:

<TextBlock Name="sometextblock" Text="sample text"/>
Run Code Online (Sandbox Code Playgroud)

在代码中我有一个具有该名称的字符串变量:

string elementName = "sometextblock";
Run Code Online (Sandbox Code Playgroud)

如何使用此变量获取此元素?我需要访问元素的属性,例如,我需要能够更改Text属性.

这该怎么做?

谢谢!

Soh*_*Ali 8

如果您在XAML中命名了元素,如下所示:

<TextBlock x:Name="sometextblock" />
Run Code Online (Sandbox Code Playgroud)

您可以通过FindName方法找到它们:

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


string elementName = txt.xyzproperty //do what you want with using txt.xyz property
Run Code Online (Sandbox Code Playgroud)