在 UserControl 中设置 ImageSource 不起作用

Set ImageSource in UserControl doesnt work

我有一个经常使用的大型控件(一堆标签等),我想将其提取为 UserControl。

之前的工作代码:

       <Image Source="/Images/MainWindow/Label.png" Width="20" Height="20" />

现在编码:

新建用户控件xaml:

         <Image Source="{Binding ImageSource}" Width="20" Height="20" />

用户控件属性:

        public ImageSource ImageSource { get; set; }

UC 调用:

        <uc:TitleUC x:Name="TitleBar" ImageSource="/Images/MainWindow/Label.png" />

遗憾的是图像没有显示,我找不到任何信息为什么不显示或如何调试它。

UserControl 中的绑定 XAML 应该使用 UserControl 实例作为源对象,而不是当前的 DataContext:

<Image Source="{Binding ImageSource,
                RelativeSource={RelativeSource AncestorType=UserControl}}" .../>

您还应该将 ItemsSource 属性 声明为依赖项 属性,以便使其可绑定并能够通过 Setter 在样式或触发器。