我想使用附加的属性来设置多个子元素的属性。仅在初始化期间,VisualTreeHelper.GetChildrenCount(parent)
返回0个子项。
当视图渲染后绑定MyText发生更改时,所有操作都会按预期进行。
如何在渲染之前对孩子们进行重新渲染?
XAML:
<StackPanel local:SetTextService.Text="{Binding MyText}">
<TextBox />
<TextBox />
<TextBox />
</StackPanel>
C#:
public class SetTextService : DependencyObject
{
public static readonly DependencyProperty TextProperty =
DependencyProperty.RegisterAttached("Text", typeof(string), typeof(SetTextService),
new FrameworkPropertyMetadata("", new PropertyChangedCallback(TextPropertyChanged)));
public static void SetText(UIElement element, string value)
{
element.SetValue(TextProperty, value);
}
public static string GetText(UIElement element)
{
return (string)element.GetValue(TextProperty);
}
private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SetChildControlText(d, (string)e.NewValue);
}
private static void SetChildControlText(DependencyObject parent, string text)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
PropertyInfo propInfo = child.GetType().GetProperty("Text");
if (propInfo != null) propInfo.SetValue(child, text);
SetChildControlText(child, text);
}
}
}
在添加TextBoxes
之前,您的附加属性已设置。您可以处理StackPanel
的Loaded
事件,并在此事件处理程序中进行处理,而不是在属性更改回调中进行处理;也可以在添加了TextBoxes
之后使用以下元素语法设置附加属性:
<StackPanel>
<TextBox />
<TextBox />
<TextBox />
<local:SetTextService.Text>
<Binding Path="MyText" />
</local:SetTextService.Text>
</StackPanel>
设置属性的顺序很重要。