带有嵌入式图像的WPF用户控件未显示该图像 [英] WPF User Control with embedded image is not displaying the image
问题描述
我创建了一个名为ImageButton的用户控件.在Generic.xaml中,控件的模板包含一个带有图片的按钮.在后面的代码中,我创建了一个名为Source的DependencyProperty,类型为ImageSource.在模板中 xaml,图片的Source属性是绑定到用户控件的source属性的模板.这是XAML:
I've created a user control called an ImageButton. In Generic.xaml, the template for the control contans a Button with an Image in it. In the code behind, I created a DependencyProperty called Source of type ImageSource. In the Template xaml, the Image's Source property is template bound to the user control's source property. Here's the XAML:
<Style TargetType="{x:Type local:ImageButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ImageButton}">
<Button Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Clip="{TemplateBinding Clip}"
ClipToBounds="{TemplateBinding ClipToBounds}"
FlowDirection="{TemplateBinding FlowDirection}"
Height="{TemplateBinding Height}"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Margin}"
MaxHeight="{TemplateBinding MaxHeight}"
MaxWidth="{TemplateBinding MaxWidth}"
MinHeight="{TemplateBinding MinHeight}"
MinWidth="{TemplateBinding MinWidth}"
Opacity="{TemplateBinding Opacity}"
OpacityMask="{TemplateBinding OpacityMask}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
ToolTip="{TemplateBinding ToolTip}"
VerticalAlignment="{TemplateBinding VerticalAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
Visibility="{TemplateBinding Visibility}"
Width="{TemplateBinding Width}" >
<Image Name="Image"
HorizontalAlignment="Stretch"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Source="{TemplateBinding Source}"
Stretch="Uniform"
VerticalAlignment="Stretch" />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
推荐答案
最有可能是您从数据库读取图像的代码遇到了一些问题,因为我已经测试了您的ImageButton控件,并使用以下代码加载了图像
Most probably your code for reading the image from database has some problem, as I have tested your ImageButton control and image get load using following code
BitmapImage bmp = 新 BitmapImage (新  ; Uri ( @" C:\ Photos.jpg"))); btn.Source = bmp;
BitmapImage bmp = new BitmapImage(new Uri(@"C:\Photos.jpg")); btn.Source = bmp;
尝试像下面的代码一样使用BeginInit和EndInit
Try using BeginInit and EndInit like following code
MemoryStream ms = ReadFromDatabase();
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = ms; //ms is memory stream
bmp.EndInit();
btn.Source = bmp;
如果上述代码不能解决您的问题,请发布您的代码以从数据库读取图像
Post your code to read image from database if above code doesn't solve your problem
这篇关于带有嵌入式图像的WPF用户控件未显示该图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!