Wpf DependencyProperty在自定义UserControl上不起作用
我有一些不起作用的简单依赖属性。我已经检查了它们,检查了我过去使用过的代码,我不确定它们为什么不工作 我有一个扩展UserControl的自定义基类MyBaseControl,然后我的自定义UI控件在此基础上进行扩展。例如,MyCustomControl扩展了MyBaseControl MyCustomControl XAML非常简单:Wpf DependencyProperty在自定义UserControl上不起作用,wpf,user-controls,wpf-controls,dependency-properties,Wpf,User Controls,Wpf Controls,Dependency Properties,我有一些不起作用的简单依赖属性。我已经检查了它们,检查了我过去使用过的代码,我不确定它们为什么不工作 我有一个扩展UserControl的自定义基类MyBaseControl,然后我的自定义UI控件在此基础上进行扩展。例如,MyCustomControl扩展了MyBaseControl MyCustomControl XAML非常简单: <StackPanel> <Image Source="{Binding Icon}" /> <TextBlock
<StackPanel>
<Image Source="{Binding Icon}" />
<TextBlock Text="{Binding Blurb}" />
</StackPanel>
请注意,我尝试了几种不同的方法来定义DependencyProperty。两者都不起作用
我通过以下方式调用我的控件:
<ctrl:MyCustomControl Height="240" VerticalAlignment="Center" HorizontalAlignment="Center" Width="320" Blurb="Slide Show" Icon="pack://application:,,,/Resources/photo_scenery.png" />
如果我直接在XAML中设置源代码或文本,它们会显示得很好。绑定只是不想正常工作
我遗漏了什么不允许绑定通过
谢谢你的帮助
更新:我已根据我尝试过的注释和其他更改更新了代码。您注册的图标属性不正确。在其注册方法中,您需要指定DP名称,即在IconProperty的位置,它应该是Icon- 另外,尝试在绑定中设置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>
您注册的图标属性不正确。在其注册方法中,您需要指定DP名称,即在IconProperty的位置,它应该是Icon- 另外,尝试在绑定中设置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>
或者,与Rohit Vats建议的设置RelativeSource不同,您可以通过如下更新代码来解决此问题
<StackPanel>
<Image Name="imgImage" Source="{Binding Icon}" />
<TextBlock Name="txtTextBlock" Text="{Binding Blurb}" />
</StackPanel>
或者,与Rohit Vats建议的设置RelativeSource不同,您可以通过如下更新代码来解决此问题
<StackPanel>
<Image Name="imgImage" Source="{Binding Icon}" />
<TextBlock Name="txtTextBlock" Text="{Binding Blurb}" />
</StackPanel>
谢谢你。我已经准备好为错过这一点而挥舞拳头,但看起来我的代码至少有两个问题。我做了上述更改,但仍然没有看到我的图像。我已更新了答案。您需要为绑定指定relativeSource。绑定上的relativeSource做到了这一点。非常感谢。我将需要再次阅读所有这些正在做的事情——因为我不理解它们的必要性,但它现在起作用了!再次感谢!谢谢你。我已经准备好为错过这一点而挥舞拳头,但看起来我的代码至少有两个问题。我做了上述更改,但仍然没有看到我的图像。我已更新了答案。您需要为绑定指定relativeSource。绑定上的relativeSource做到了这一点。非常感谢。我将需要再次阅读所有这些正在做的事情——因为我不理解它们的必要性,但它现在起作用了!再次感谢!
public LabeledTextBox()
{
InitializeComponent();
imgImage.DataContext = this;
txtTextBlock.DataContext = this;
}