C# WPF子定义的附加属性初始值

C# WPF子定义的附加属性初始值,c#,wpf,attached-properties,C#,Wpf,Attached Properties,我想使用附加属性来设置多个子元素的属性。仅在初始化期间,VisualTreeHelper.GetChildrenCount(父项)返回0个子项 在呈现视图后更改绑定MyText时,所有操作均按预期进行 在渲染之前,我如何对孩子进行评分 XAML: C#: public类SetTextService:DependencyObject { 公共静态只读DependencyProperty TextProperty= DependencyProperty.RegisterAttached(“文本”

我想使用附加属性来设置多个子元素的属性。仅在初始化期间,
VisualTreeHelper.GetChildrenCount(父项)
返回0个子项

在呈现视图后更改绑定MyText时,所有操作均按预期进行

在渲染之前,我如何对孩子进行评分

XAML:


C#:

public类SetTextService:DependencyObject
{
公共静态只读DependencyProperty TextProperty=
DependencyProperty.RegisterAttached(“文本”、typeof(字符串)、typeof(SetTextService),
新的FrameworkPropertyMetadata(“,新的PropertyChangedCallback(TextPropertyChanged));
公共静态void SetText(UIElement元素,字符串值)
{
元素.SetValue(TextProperty,value);
}
公共静态字符串GetText(UIElement)
{
返回(字符串)元素.GetValue(TextProperty);
}
私有静态void TextPropertyChanged(DependencyObject d、DependencyPropertyChangedEventArgs e)
{
SetChildControlText(d,(string)e.NewValue);
}
私有静态void SetChildControlText(DependencyObject父对象,字符串文本)
{
for(int i=0;i
在添加
文本框之前设置附加属性。您可以处理
StackPanel
Loaded
事件,并在此事件处理程序中进行处理,而不是在property changed回调中进行处理,也可以在使用以下元素语法添加
文本框后设置附加属性:

<StackPanel>
    <TextBox />
    <TextBox />
    <TextBox />
    <local:SetTextService.Text>
        <Binding Path="MyText" />
    </local:SetTextService.Text>
</StackPanel>


属性设置的顺序很重要。

由于该服务可以用于比StackPanel更多的类型,使用第二个选项解决了我的问题。
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);
        }
    }
}
<StackPanel>
    <TextBox />
    <TextBox />
    <TextBox />
    <local:SetTextService.Text>
        <Binding Path="MyText" />
    </local:SetTextService.Text>
</StackPanel>