简体   繁体   English

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

[英]WPF Child defined attached property initial value

I would like to use an attached property to set properties of multiple child elements. 我想使用附加属性来设置多个子元素的属性。 Only during initialisation the VisualTreeHelper.GetChildrenCount(parent) returns 0 children. 仅在初始化期间, VisualTreeHelper.GetChildrenCount(parent)返回0个孩子。

When the binding MyText is changed after the view is rendered, all works as expected. 呈现视图后更改绑定MyText时,所有工作均按预期进行。

How can I itterate the children before rendering? 在渲染之前如何使孩子们感到烦恼?

XAML: XAML:

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

C#: 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);
        }
    }
}

Your attached property is set before the TextBoxes are added. 添加TextBoxes 之前 ,已设置您的附加属性。 You could either handle the Loaded event of the StackPanel and do the processing in this event handler instead of doing it in the property changed callback, or you can set your attached property after the TextBoxes have been added using the following element syntax: 您可以处理StackPanelLoaded事件并在此事件处理程序中进行处理,而不是在属性更改后的回调中进行处理,也可以使用以下元素语法添加TextBoxes 之后设置附加属性:

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

The order in which the properties are set matters. 属性的设置顺序很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM