【发布时间】:2014-10-23 18:35:24
【问题描述】:
我正在使用 Visual Studio 2013 WPF 和 MVVM 模式。
我有一个模块化解决方案,在 1 个项目解决方案中我有很多项目。
-
Common.Library(类库)
这基本上是我的库,它将包含所有基本内容,例如 ViewModelBase.cs 类实现 INotifyPropertyChanged。我还有一个包含图像(jpg、png 等)的 Images 文件夹和另一个名为 BinaryImageConverter.cs 的类,用于将二进制图像转换为 BitmapImages
-
客户(WPF 项目)
在这里,我有一个用户控件,其中包含一个图像控件。我得到了我的模型/视图/视图模型
客户模型:视图模型库
private BitmapImage _ProfilePicture;
private BitmapImage ProfilePicture
{
get { return this._ProfilePicture; }
set
{
if (this._ProfilePicture == value)
return;
this._ProfilePicture = value;
OnPropertyChanged("ProfilePicture");
}
}
BinaryImageConverter.cs
public BitmapImage BinaryPictureConverter(byte[] Picture)
{
BitmapImage Image;
if (Picture == null)
return null;
Image = new BitmapImage();
using (MemoryStream imageStream = new MemoryStream())
{
imageStream.Write(Picture, 0, Picture.Length);
imageStream.Seek(0, SeekOrigin.Begin);
Image.BeginInit();
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.StreamSource = imageStream;
Image.EndInit();
Image.Freeze();
}
return Image;
}
CustomerView.xaml
<UserControl.Resources>
<ResourceDictionary>
<BitmapImage x:Key="DefaultCustomerPicture" UriSource="/Common.Library;component/Images/DefaultCustomerPicture.jpg" />
</ResourceDictionary>
</UserControl.Resources>
<Image Name="ImgProfile" Width="150" HorizontalAlignment="Left" DockPanel.Dock="Left" Source="{Binding Path=CustomerProfile.ProfilePicture, TargetNullValue={StaticResource DefaultCustomerPicture}}" Stretch="Fill" />
我有一个 varbinary 字段来将我的图像存储在数据库中。
所以我将我的数据加载到我的 CustomerViewModel 中。一切都显示除了我的用户控件上的图像。 我显示了完美的名字和姓氏,但图像没有出现。
编辑: 忘了提到我的用户控件加载在 ListBox 中,并且 ItemSource 绑定到我的 CustomerProfile,它是 CustomerModel 的 ObservableCollection
<ListBox Name="listCustomers" Background="Transparent" BorderThickness="0" Margin="5,10,0,0" ItemsSource="{Binding Path=CustomerProfile}">
<ListBox.ItemTemplate>
<DataTemplate>
<vw:CustomerView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
【问题讨论】:
-
为什么不直接从字节数组创建 MemoryStream,比如
new MemoryStream(Picture),从而避免了 Write and Seek?BinaryPictureConverter是否在任何地方使用过? -
您的
byte[]数组是编码图像(例如,PNG、JPG 或 BMP 等图像格式),还是原始位图数据? -
BinaryPictureConverter从数据库接收图片(我将图像存储在客户表中的 varbinary 字段中),查看客户时,它将 varbinary 更改为 BitmapImage,以便我可以显示它,现在我的问题是当表中的 varbinary 字段为空时,我需要显示默认图像,它位于 Common.Library 程序集中,我尝试使用 FallbackValue 和 TargetNullValue 但没有成功我没有得到任何Xaml 或运行时错误,当我插入 FallbackValue 时,我什至可以看到图片,但在运行时对于没有图片的客户没有任何显示。
标签: c# wpf mvvm visual-studio-2013 bitmapimage