您可以用FindChild()
訪問Button
:
上市的功能:
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
if (parent == null)
{
return null;
}
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null) break;
}
else
if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement.Name == childName)
{
foundChild = (T)child;
break;
}
else
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null)
{
break;
}
}
}
else
{
foundChild = (T)child;
break;
}
}
return foundChild;
}
呼叫被製造成:
private void btnSource_Click(object sender, RoutedEventArgs e)
{
Button MyBtnTarget = FindChild<Button>(listOfParents, "btnTarget");
MessageBox.Show(MyBtnTarget.Content.ToString());
}
但這種方式,該功能將選擇第一個按鈕,我們需要訪問所有的元素。爲此,我重寫了該函數,以便它返回列表中的所有元素。下面的代碼:
public static void FindChildGroup<T>(DependencyObject parent, string childName, ref List<T> list) where T : DependencyObject
{
// Checks should be made, but preferably one time before calling.
// And here it is assumed that the programmer has taken into
// account all of these conditions and checks are not needed.
//if ((parent == null) || (childName == null) || (<Type T is not inheritable from FrameworkElement>))
//{
// return;
//}
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
// Get the child
var child = VisualTreeHelper.GetChild(parent, i);
// Compare on conformity the type
T child_Test = child as T;
// Not compare - go next
if (child_Test == null)
{
// Go the deep
FindChildGroup<T>(child, childName, ref list);
}
else
{
// If match, then check the name of the item
FrameworkElement child_Element = child_Test as FrameworkElement;
if (child_Element.Name == childName)
{
// Found
list.Add(child_Test);
}
// We are looking for further, perhaps there are
// children with the same name
FindChildGroup<T>(child, childName, ref list);
}
}
return;
}
}
調用函數:
private void btnSource_Click(object sender, RoutedEventArgs e)
{
// Create the List of Button
List<Button> list = new List<Button>();
// Find all elements
FindChildGroup<Button>(listOfParents, "btnTarget", ref list);
string text = "";
foreach (Button elem in list)
{
text += elem.Content.ToString() + "\n";
}
MessageBox.Show(text, "Text in Button");
}
一般有幾種方式來訪問模板。這裏有一個:How to use FindName with a ContentControl。