例如,我有一个UIElement:
<TextBlock Name="sometextblock" Text="sample text"/>
在代码中我有一个带有该名称的字符串变量:
string elementName = "sometextblock";
如何使用此变量获取此元素?我需要访问元素的属性,例如,我需要能够更改Text属性。
怎么做?
谢谢!
答案 0 :(得分:5)
如果您在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
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
假设您已经在XAML上使用了它:
string[] NameControls = { "MyButton1", "MyButton2", "MyImage1", "MyTextBox1", "MyTextBox2", "MyButton3" };
您必须将控件的名称放在字符串数组中,所以:
for (int i = 0; i < NameControls.Length; i++)
{
dynamic MyControl = this.FindName(NameControls[i]);
// do something
}
然后,您可以迭代控件并访问属性:
dynamic MyControl = this.FindName(NameControls[i]);
MyControl.Opacity = 0.7;
例如,在我的情况下,我需要更改确定控件的不透明度,因此,在for块中,我将其设置为:
R
答案 3 :(得分:0)
您可以参考此方法:
public static bool FindVisualChildByName<T>(this DependencyObject parent, string name, out T control) where T : DependencyObject
{
if (parent == null)
throw new ArgumentNullException(nameof(parent), "Control cấp cha không được null.");
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name), "Tên của control cần tìm không được null hoặc empty.");
var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
var controlName = child.GetValue(FrameworkElement.NameProperty) as string;
if (controlName == name)
{
control = child as T;
return true;
}
if (FindVisualChildByName(child, name, out control)) return true;
}
control = null;
return false;
}