带有图像的WPF自定义控件。

带有图像的WPF自定义控件。,wpf,image,xaml,custom-controls,Wpf,Image,Xaml,Custom Controls,我对WPF/XAML相当陌生,目前我面临一个问题 我有一个包含两个项目的解决方案,第一个项目是一个自定义控件库,里面有一个自定义窗体控件。第二个项目是使用自定义窗口表单的WPF应用程序 除表单图标外,所有操作正常。在WPF应用程序项目中,我将窗口图标属性设置为/ProjectTwoNameSpace;component/Resources/Images/Film.ico,在WPF自定义控件中,我尝试以这种方式显示该图像: <Image Grid.Column="0" Margin="3"

我对
WPF/XAML
相当陌生,目前我面临一个问题

我有一个包含两个项目的解决方案,第一个项目是一个自定义控件库,里面有一个自定义窗体控件。第二个项目是使用自定义窗口表单的WPF应用程序

除表单图标外,所有操作正常。在WPF应用程序项目中,我将窗口图标属性设置为
/ProjectTwoNameSpace;component/Resources/Images/Film.ico
,在WPF自定义控件中,我尝试以这种方式显示该图像:

<Image Grid.Column="0" Margin="3" Width="27" Height="27">
     <Image.Source>
        <BitmapImage UriSource="{Binding Path=Icon}" />
     </Image.Source>
 </Image>

但它不起作用,我在运行时收到一个错误,指出必须为我的
标记设置属性
UriSource
StreamSource


有人能帮我吗?我认为这是一个WPF新手的问题。

无法如您所示设置
BitmapImage
UriSource
属性,因为它是Uri类型,您正在尝试将其设置为字符串。我想说,完成您正在做的事情的最简单方法是将Image.Source绑定到Icon,然后将字符串转换为位图图像对象。假设您的控件在窗口中,这看起来像这样

<Window.Resources>
    <converters:StringToBitmapImageConverter x:Key="stringToBitmapImageConverter" />
</Window.Resources>

...

<Image Grid.Column="0" Margin="3" Width="27" Height="27"
    Source="{Binding Path=Icon, Converter={StaticResource stringToBitmapImageConverter}}">
</Image>

您的解决方案是好的,但是您关于UriSource“不能通过数据绑定设置”的陈述是不真实的。您可以将Uri源绑定到Uri类型的属性。您不能在没有转换器的情况下将其绑定到字符串属性。我在尝试粘贴标记时出错,该标记表示在窗口类型中找不到属性资源。我应该将这个XAML代码粘贴到哪里?它对我不起作用,我没有得到编译错误,但是图像不在那里。icon属性设置正确,因为我可以在任务栏中看到图标,但在自定义控件中看不到。问题可能是因为我的icon属性设置为WPF应用程序命名空间,而在WPF控件库命名空间中找不到?
class StringToBitmapImageConverter: IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.UriSource = new Uri(value as string);
        image.EndInit();

        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}