带图像的WPF自定义控件。 [英] WPF Custom Control with Image.
问题描述
我是 WPF / XAML
的新手,我目前遇到了问题。
I am quite new to WPF/XAML
and I am currently facing a problem.
我有一个其中包含两个项目的解决方案,第一个项目是自定义控件库,里面有自定义窗体控件。第二个项目是使用我的自定义窗口表单的WPF应用程序。
I have a solution with two projects in it, the first project is a Custom Control Library with a custom Window form control inside. The second project is a WPF application using my custom window form.
除表单Icon外,所有工作正常。在WPF应用程序项目中,我将窗口图标属性设置为 /ProjectTwoNameSpace;component/Resources/Images/Film.ico
,并在WPF自定义控件中我尝试显示该图像那样:
All work fine except for the form Icon. In the WPF application project I set my window icon property to /ProjectTwoNameSpace;component/Resources/Images/Film.ico
, and in the WPF custom control I try to show that image that way :
<Image Grid.Column="0" Margin="3" Width="27" Height="27">
<Image.Source>
<BitmapImage UriSource="{Binding Path=Icon}" />
</Image.Source>
</Image>
但是它不起作用,我在运行时遇到错误,说该属性 UriSource
或 StreamSource
必须为我的< Image>
标记设置。
But it doesn't work, I get a error at runtime saying that the property UriSource
or StreamSource
must be set for my <Image>
tag.
任何人都可以帮助我吗?我认为这是一个WPF新手问题。
Anyone can help me ? I think it's jsut a WPF newbie problem.
推荐答案
UriSource
属性无法设置 BitmapImage
,因为它是Uri类型,并且您正在尝试将其设置为字符串。我想说完成你正在做的最简单的方法是将你的Image.Source绑定到Icon,然后将字符串转换为位图Image对象。假设您的控件在窗口中,这看起来像这样
The UriSource
property of a BitmapImage
cannot be set as you have shown because it is of type Uri and you are trying to set it to a string. I'd say the easiest way to accomplish what you're doing is to bind your Image.Source to Icon, and then convert the string to a bitmap Image object. Assuming your control is in a window, this would look something like this
<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>
然后转换器看起来像:
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
}
这篇关于带图像的WPF自定义控件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!