I have 3 projects: Data (Entities, DbContext, etc) WebAPI (ASP.NET CORE) Desktop admin client (WPF, mvvm)
I have books with images.
With the API I can get the images (which are byte []) and books from Data project. At The admin client at the ViewModel I can see the proper byte[] to the proper.
But I don't know how to display at my window.
Relevant code:
MainWindow.xaml
<StackPanel Grid.Row="2" Orientation="Horizontal" Width="600">
<TextBlock Text="Book ID: " Margin="1" />
<TextBox Width="50" Text="{Binding BookIdProp}" Margin="0" />
<Button Content="Show image" Command="{Binding ShowBookImage}" Width="114" IsEnabled="{Binding IsLoaded}" />
</StackPanel>
I want to show the image here:
<ListBox Grid.Row="3" Grid.ColumnSpan="2" Name="imageListBox" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="100" Width="Auto" Source="{Binding ShowImageCommand, Converter={StaticResource bookImageConverter}}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
At the viewmodel now I can get the byte[] of image by bookId (textbox). I'm using data transfer objects.
DTO's:
public class ImageDTO
{
public int Id { get; set; }
public int BookId { get; set; }
public byte[] ImageContent { get; set; }
}
public class BookDTO
{
public int Id { get; set; }
public String Title { get; set; }
public String Author { get; set; }
public ImageDTO Image { get; set; }
public BookDTO()
{
Image = new ImageDTO();
}
}
ViewModel:
public DelegateCommand ShowImageCommand{ get; private set; }
ShowImageCommand= new ShowImageCommand(param => ShowImage());
private void ShowImage(int id)
{
??
}
Converter:
public object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
{
if (!(value is Byte[]))
return Binding.DoNothing;
try
{
using (MemoryStream stream = new MemoryStream(value as Byte[]))
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
return image;
}
}
catch
{
return Binding.DoNothing;
}
}
public object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
How to bind at the viewmodel to show the proper image?