Reputation: 601
I'm still tyring to get my head around MVVM. I got stuck on displaying my images which paths are stored in an observableCollection. In the past I could make it would with code behind in the view but now when I'm trying to implement MVVM on my project and it doesn't show any images anymore.
This is the code I have in the viewmodel
private ObservableCollection<Image> _selectedImageList = new ObservableCollection<Image>();
public ObservableCollection<Image> SelectedImageList
{
get { return _findImageList; }
set { _findImageList = value; }
}
public ImageLibraryViewModel()
{
string dbConnectionString = @"Data Source =movieprepper.sqlite;";
SQLiteConnection cnn = new SQLiteConnection(dbConnectionString);
cnn.Open();
string Query = "Select* from images";
SQLiteDataAdapter sda = new SQLiteDataAdapter(Query, cnn);
DataTable dt = new DataTable();
sda.Fill(dt);
cnn.Close();
foreach (DataRow row in dt.Rows)
{
string path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, (AppDomain.CurrentDomain.BaseDirectory.Length - 10));
string name = row["path"].ToString();
Uri uri = new Uri(path + name);
Image I = new Image(uri.ToString(), row["path"].ToString(), row["title"].ToString());
SelectedImageList.Add(I);
}
}
And this is what I have in the XAML
<ListBox ItemsSource="{Binding SelectedImageList}" dd:DragDrop.IsDropTarget="True">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Thumbnail}" Width="200"/>
<TextBox Text="{Binding Thumbnail}"></TextBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In the text that's binded to the thumbnail I can clearly read the path to which the image points at, but the image doesn't display in the list. In the past without the MVVM, the Image Source converted the filepath automatically into an image. Does Anybody know where I went wrong? Thanks for your help.
Upvotes: 0
Views: 2794
Reputation: 61369
ImageSource
does not actually convert from a string at runtime all that well. In fact, you likely have a couple System.Data
exceptions indicating that the conversion is failing.
What you will usually do here is use an IValueConverter
to take your path and make a BitmapImage
out of it.
Your XAML becomes:
<Image Source="{Binding ThumbnailPath, Converter={StaticResource PathToImageConverter}"/>
The Convert
method in the converter would be something like:
public object Convert(...)
{
return new BitmapImage(new Uri((string)value));
}
Upvotes: 1