簡體   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