我有一些简单的依赖属性不工作。我查看过他们,查看了我过去使用的代码,但我不确定他们为什么不工作。DependencyProperty不工作在自定义UserControl
我有一个自定义的基类(MyBaseControl),它扩展了UserControl,然后我的自定义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设置源或文本,它们显示了就好了。绑定只是不想正常工作。
我错过了什么,不允许我的绑定通过?
谢谢你的帮助!
更新:我更新了基于评论和我试过的其他更改的代码。
谢谢RV1987。我准备在空中摇摆我的拳头,因为我的代码看起来至少有两个问题。我做了上述改变,但仍然没有看到我的形象。 – 2012-07-19 18:17:37
我已经更新了答案。您需要为您的绑定指定relativeSource。 – 2012-07-19 18:24:00
绑定上的RelativeSource做到了。谢谢!我将需要重新阅读所有这些内容 - 因为我不了解他们的需求,但现在它仍然有效!再次感谢! – 2012-07-19 18:27:46