Current.MainWindow
是在任何情況下理想的,因爲如果UserControl
被嵌入到另一個UserControl
,你仍然可以使用Current.MainWindow
向上遍歷樹。所有的方法都很好,這一切都取決於使用情況和你想要完成的。
要訪問UserControl
內的控件(可以說TextBlock)。
TextBlock tb = FindVisualChildren<TextBlock>(usercontrol)
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}