【问题标题】:Windows Phone - using DependencyProperty within UserControl xamlWindows Phone - 在 UserControl xaml 中使用 DependencyProperty
【发布时间】:2012-12-09 17:19:27
【问题描述】:

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} 不起作用,在这种情况下该怎么办?

【问题讨论】:

    标签: c# silverlight windows-phone-7 xaml dependency-properties


    【解决方案1】:

    它不起作用的原因是您将Fill 绑定到Color 类型的属性 - 而Fill 应该使用Brush 类型的属性。这是在您使用原始 xaml 时为您处理的转换 - 也就是说,如果您输入 Fill="Red",运行时实际上会根据您指定的颜色名称创建一个 SolidColorBrush

    您应该修改您的控件以将属性设置为Brush,或者根据您设置的颜色自动创建Brush

    您可以使用一个属性来标记您的属性,该属性会提示 Xaml 应该使用此转换,但我不记得它是什么。 (如果我以后能找到它,我会编辑它。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2012-06-06
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多