简体   繁体   中英

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>

So why {Binding MyDp, ElementName=Uc} doesn't work and what to do in this case?

The reason it doesn't work is that you're binding Fill to a property of type Color - and Fill should instead take a property of type Brush . This is a conversion that's handled for you when you work with raw xaml - that is, if you put Fill="Red" the runtime will actually create a SolidColorBrush from the color name you specify.

You should modify your control to either make the property a Brush , or instead to auto-create a Brush from the color you're setting.

There is an attribute you can mark up your property with that will hint to the Xaml that this conversion should be used, but I can't recall offhand what it is. (I'll edit if I can find it later.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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