簡體   English   中英

WPF中的DependencyProperty和UserControl

[英]DependencyProperty and UserControl in WPF

我創建了一個帶有2個網格行內的Label和Rectangle的UserControl。 我添加了財產

public string SetText
{
    get
    {
        return (string)GetValue(mLabel.ContentProperty);
    }
    set
    {
        SetValue(mLabel.ContentProperty, value);
    }
}

物業用途

<local:PlayerMiniImage SetText="Player 1" ...

使用該屬性時,標簽的字體更改了,矩形消失了,有什么想法嗎?

如果定義UserControl ...

<UserControl x:Class="...">
    <Border>
        <!-- ... -->
    </Border>
</UserControl>

然后,其中的所有內容(這里是Border )就是Content ,因此,如果您設置ContentProperty所有內容都將被替換。


要設置標簽內容,請創建一個新的DP:

public static readonly DependencyProperty LabelContentProperty =
    DependencyProperty.Register("LabelContent", typeof(object), typeof(MyUserControl), new UIPropertyMetadata(null));
public object LabelContent
{
    get { return (object)GetValue(LabelContentProperty); }
    set { SetValue(LabelContentProperty, value); }
}

並將標簽綁定到它:

<Label Content="{Binding LabelContent, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

暫無
暫無

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

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