DependencyProperty无法处理自定义UserControl

时间:2012-07-19 17:34:33

标签: wpf user-controls wpf-controls dependency-properties

我有一些不起作用的简单依赖属性。我查看了它们,查看了我过去使用的代码,我不确定它们为什么不工作。

我有一个扩展UserControl的自定义基类(MyBaseControl),然后我的自定义UI控件就会扩展。例如,MyCustomControl扩展了MyBaseControl。

MyCustomControl XAML很简单:

<StackPanel>
    <Image Source="{Binding Icon}" />
    <TextBlock Text="{Binding Blurb}" />
</StackPanel>

MyCustomControl代码如下所示:

public partial class MyCustomControl: MyBaseControl
{
    //public static readonly DependencyProperty IconProperty = Image.SourceProperty.AddOwner(typeof(MyCustomControl));
    //public static readonly DependencyProperty BlurbProperty = TextBlock.TextProperty.AddOwner(typeof(MyCustomControl));

    public static readonly DependencyProperty IconProperty =
        DependencyProperty.Register(
        "Icon",
        typeof(ImageSource),
        typeof(MyCustomControl),
        new PropertyMetadata(null));

    public static readonly DependencyProperty BlurbProperty =
        DependencyProperty.Register(
        "Blurb",
        typeof(String),
        typeof(MyCustomControl),
        new PropertyMetadata(null));

    public MyCustomControl() : base()
    {
        InitializeComponent();
    }

    #region Properties

    public ImageSource Icon
    {
        get { return (ImageSource)GetValue(IconProperty); }
        set { SetValue(IconProperty, value); }
    }

    public String Blurb
    {
        get { return (String)GetValue(BlurbProperty); }
        set { SetValue(BlurbProperty, value); }
    }

    #endregion Properties
}

请注意,我尝试了几种不同的方法来定义DependencyProperty。两者都不起作用。

我用以下方式打电话给我的控件:

<ctrl:MyCustomControl Height="240" VerticalAlignment="Center" HorizontalAlignment="Center" Width="320" Blurb="Slide Show" Icon="pack://application:,,,/Resources/photo_scenery.png" />

如果我直接在XAML中设置了源或文本,它们会很好地显示出来。绑定只是不想正常工作。

我错过了哪些不允许我的绑定通过?

感谢您的帮助!

更新:我已根据我尝试过的评论和其他更改更新了代码。

2 个答案:

答案 0 :(得分:4)

您正在错误地注册Icon属性。在其注册方法中,您需要指定DP名称,即代替“IconProperty”,它应该是“Icon” -

public static readonly DependencyProperty IconProperty =
        DependencyProperty.Register(
        "Icon",
        typeof(ImageSource),
        typeof(MyCustomControl),
        new PropertyMetadata(null));

另外,尝试在这样的绑定中设置RelativeSource -

<StackPanel>
    <Image Source="{Binding Icon, RelativeSource={RelativeSource 
            Mode=FindAncestor, AncestorType={x:Type ctrl:MyCustomControl}}}" />
    <TextBlock Text="{Binding Blurb, RelativeSource={RelativeSource 
            Mode=FindAncestor, AncestorType={x:Type ctrl:MyCustomControl}}}" />
</StackPanel>

答案 1 :(得分:0)

或者,您可以通过更新代码来解决问题,而不是按照Rohit Vats的建议设置RelativeSource

public LabeledTextBox()
{
    InitializeComponent();
    imgImage.DataContext = this;
    txtTextBlock.DataContext = this;
}

Update dbo.tablename set class=1 where membership between 0 and 4