2014-02-27 78 views
1

例如,我有一個的UIElement:如何通過名稱存儲在字符串變量中獲取XAML元素?

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

在代碼中,我有一個同名的字符串變量:

string elementName = "sometextblock"; 

如何得到這個元素,使用這個變量?我需要訪問元素的屬性,例如,我需要能夠更改Text屬性。

如何做到這一點?

謝謝!

回答

3

如果命名在XAML元素如下:

<TextBlock x:Name="sometextblock" /> 

你可以通過FindName方法找到它們:

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


string elementName = txt.xyzproperty //do what you want with using txt.xyz property 
0

您可以使用此方法:

var textBlock = FindChild<TextBlock>(Application.Current.RootVisual, "sometextblock"); 

和FindChild方法是:

public static T FindChild<T>(DependencyObject parent, string childName) 
     where T : DependencyObject 
    { 
     // Confirm parent and childName are valid. 
     if (parent == null) 
     { 
      return null; 
     } 

     T foundChild = null; 

     int childrenCount = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < childrenCount; i++) 
     { 
      DependencyObject child = VisualTreeHelper.GetChild(parent, i); 
      // If the child is not of the request child type child 
      var childType = child as T; 
      if (childType == null) 
      { 
       // recursively drill down the tree 
       foundChild = FindChild<T>(child, childName); 

       // If the child is found, break so we do not overwrite the found child. 
       if (foundChild != null) 
       { 
        break; 
       } 
      } 
      else if (!string.IsNullOrEmpty(childName)) 
      { 
       var frameworkElement = child as FrameworkElement; 
       // If the child's name is set for search 
       if (frameworkElement != null && frameworkElement.Name == childName) 
       { 
        // if the child's name is of the request name 
        foundChild = (T) child; 
        break; 
       } 

       // Need this in case the element we want is nested 
       // in another element of the same type 
       foundChild = FindChild<T>(child, childName); 
      } 
      else 
      { 
       // child element found. 
       foundChild = (T) child; 
       break; 
      } 
     } 

     return foundChild; 
    } 
} 
+0

有沒有更簡單的方法? – splash27

相關問題