如何在mvvm

时间:2015-05-30 00:08:12

标签: c# wpf xaml mvvm bitmap

我仍然想要了解MVVM。 我被困在显示我的图像,哪些路径存储在observableCollection中。在过去,我可以在视图中使用代码,但现在当我尝试在我的项目上实现MVVM并且它不再显示任何图像时。

这是我在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);
        }
}

这就是我在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>

在与缩略图绑定的文本中,我可以清楚地读取图像指向的路径,但图像不会显示在列表中。在没有MVVM的情况下,Image Source会自动将文件路径转换为图像。有人知道我哪里出错吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

ImageSource实际上并没有在运行时从字符串转换。实际上,您可能会有几个System.Data个例外,表明转换失败。

您通常在这里做的是使用IValueConverter来走自己的路径并从中BitmapImage

您的XAML成为:

<Image Source="{Binding ThumbnailPath, Converter={StaticResource PathToImageConverter}"/>

转换器中的Convert方法类似于:

public object Convert(...)
{
     return new BitmapImage(new Uri((string)value));
}