繁体   English   中英

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

[英]WPF Child defined attached property initial value

我想使用附加属性来设置多个子元素的属性。 仅在初始化期间, 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 之前 ,已设置您的附加属性。 您可以处理StackPanelLoaded事件并在此事件处理程序中进行处理,而不是在属性更改后的回调中进行处理,也可以使用以下元素语法添加TextBoxes 之后设置附加属性:

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

属性的设置顺序很重要。

暂无
暂无

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

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