簡體   English   中英

Windows Phone - 在UserControl xaml中使用DependencyProperty

[英]Windows Phone - using DependencyProperty within UserControl xaml

WindowsPhoneControl1.xaml.cs:

public partial class WindowsPhoneControl1
{
    public static readonly DependencyProperty MyDpProperty =
        DependencyProperty.Register("MyDp",
                                    typeof (Color),
                                    typeof (WindowsPhoneControl1),
                                    new PropertyMetadata(default(Color)));

    public Color MyDp
    {
        get { return (Color) this.GetValue(MyDpProperty); }
        set { this.SetValue(MyDpProperty, value); }
    }
...
}

WindowsPhoneControl1.xaml:

<UserControl x:Class="MyProj.WindowsPhoneControl1" x:Name="Uc" ...>
    <Rectangle Width="200" Height="200" Fill="{Binding MyDp, ElementName=Uc}" />

    <!--<Rectangle Width="200" Height="200" Fill="Red" /> Works fine-->
</UserControl>

MainPage.xaml中:

<Grid x:Name="LayoutRoot">
    <myProj:WindowsPhoneControl1 MyDp="SandyBrown" />
</Grid>

那么為什么{Binding MyDp, ElementName=Uc}不起作用以及在這種情況下該怎么辦?

它不起作用的原因是你將Fill綁定到Color類型的屬性 - 而Fill應該取一個Brush類型的屬性。 當您使用原始xaml時,這是為您處理的轉換 - 也就是說,如果您將Fill="Red"為運行時,實際上將根據您指定的顏色名稱創建SolidColorBrush

您應該修改控件以使屬性成為Brush ,或者從您正在設置的顏色自動創建Brush

有一個屬性可以標記你的屬性,這將暗示Xaml應該使用這個轉換,但我不記得它是什么。 (我會編輯,如果我以后可以找到它。)

暫無
暫無

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

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