簡體   English   中英

WPF 用戶控件 - 如果未明確指定,則默認為另一個內置屬性的控件屬性

[英]WPF User Control - control property that defaults to another built-in property if not specified explicitly

給定一個由兩個文本塊組成的簡單用戶控件,他們會從控件的父級繼承比如說 Foreground 屬性。 但是,如果我希望控件能夠僅覆蓋第一個文本塊的前景,我可以在控件上添加一個依賴屬性(FirstBlockForeground),如果明確指定它會正常工作,但我希望它是任何值如果未指定,則為用戶控件的前景值。

<UserControl ..... x:Name="myCtrl">
   <StackPanel>
     <TextBlock Text="First" Foreground={Binding FirstBlockForeground, ElementName=myCtrl}/>
     <TextBlock Text="Second"/>
   </StackPanel>
</UserControl>

即在父母身上:

<local:myCtrl Foreground="red" FirstBlockForeground="blue"/>

工作正常。

<local:myCtrl Foreground="red" />

FirstBlockForeground 將具有默認值(在DependencyProperty.Register調用中指定),但我希望它是紅色的。

是否可以避免每次都明確指定 FirstBlockForeground?

UserControl 可以有一個帶有用於 FirstBlockForeground 屬性的 Setter 的 Style,該屬性綁定到它的 Foreground:

<UserControl x:Class="MyNamespace.MyCtrl"
             xmlns:local="clr-namespace:MyNamespace" ...>

    <UserControl.Style>
        <Style>
            <Setter Property="local:MyCtrl.FirstBlockForeground"
                    Value="{Binding Foreground,
                        RelativeSource={RelativeSource Self}}"/>
        </Style>
    </UserControl.Style>

    <StackPanel>
        <TextBlock Text="First"
                   Foreground="{Binding FirstBlockForeground,
                       RelativeSource={RelativeSource AncestorType=UserControl}}"/>
        <TextBlock Text="Second"/>
    </StackPanel>
</UserControl>

或者,您可以簡單地檢查在加載控件之前是否設置了FirstBlockForeground屬性:

public MyCtrl()
{
    InitializeComponent();

    Loaded += (s, e) =>
    {
        if (FirstBlockForeground == null)
        {
            FirstBlockForeground = Foreground;
        }
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM