我正在尝试在加载页面后更新所有文本框元素。
问题
为什么首次加载时不返回TextBox?
释
我有一个带有Frame元素的MainWindow,用于在wpf Pages之间导航 因此,当用户单击菜单项时,页面会加载到框架中 以下是用户单击MenuItem时的代码:
将新页面加载到框架中的代码(方法导航)
public static void Navigate(Page page, double fadeTime = 0.6)
{
MainWindow MainWin = (MainWindow) Application.Current.MainWindow;
Frame NavFrame = MainWin.mainFrame;
if (NavFrame.Content != page)
{
NavFrame.NavigationService.Navigate(page);
//Gebruik Dispatcher om Fadein Effect te kunnen toepassen
Frame mainFrame = NavFrame;
NavFrame.Dispatcher.BeginInvoke(
new Action(() =>
{
//Voeg Animatie Toe
NavFrame.Opacity = 0;
DoubleAnimation fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(fadeTime), FillBehavior.HoldEnd);
mainFrame.BeginAnimation(UIElement.OpacityProperty, fadeIn, HandoffBehavior.Compose);
}));
//Bij navigeren naar andere pagina roep GC aan.
GC.Collect();
}
int amount = 0;
//Apply Color on CaretBrush
foreach (TextBox tb in Worker.FindVisualChildren<TextBox>(page))
{
amount++;
tb.CaretBrush = (Brush)new BrushConverter().ConvertFromString("#FF8E9CFF");
}
Worker.ShowModernBox(amount.ToString()); //Custom messagebox
page.UpdateDefaultStyle();
page.UpdateLayout();
}
FindVisualChildren方法
//Haal alle elementen van huidige view op.
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
//Indien het object gevuld is met componenten
if (depObj != null)
{
//Voor ieder Object in huidige view
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
//geef Child terug
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T) child;
}
//geef CHilds van CHild terug.
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
问题
第一次用户加载此页面时,它返回int amount为0,当第二次单击时,我返回所有19个文本框。这是为什么?当我调试它并扩展我的页面时,我可以看到那里的文本框
答案 0 :(得分:0)
感谢Pragmateek 解决方案:将以下代码绑定到ContentRendered事件
foreach (TextBox tb in Worker.FindVisualChildren<TextBox>(page))
{
amount++;
tb.CaretBrush = (Brush)new BrushConverter().ConvertFromString("#FF8E9CFF");
}
Worker.ShowModernBox(amount.ToString()); //Custom messagebox
page.UpdateDefaultStyle();
page.UpdateLayout();
<强>原因强>
当visualTree找到元素时,内容根本不会呈现。因此,请等待页面首先呈现其所有内容,方法是将其绑定到ContentRendered事件。
积分去Pragmateek