如何通过 wpf 中的代码添加现有项目

How to add an existing item via code in wpf

我正在尝试将选定的图像复制到文件夹,然后想用图像对象显示它。复制工作正常,但是当我想显示它时,程序似乎找不到它。仅当我手动使用 "add existing Item" 时才能显示图像。有没有办法自动添加?

这是我的代码:

string name = "image1";

OpenFileDialog dialog = new OpenFileDialog();

Nullable<bool> dialogOK = dialog.ShowDialog();

if(dialogOK == true)
{
     File.Copy(dialog.FileName, @"..\..\Images\" + name + ".png", true);


     image.Source = new BitmapImage(new Uri(@"Images\" + name + ".png", UriKind.Relative));
}

("image" 定义在 xaml)

使用绝对路径加载 BitmapImage 似乎更安全:

var dialog = new OpenFileDialog();

if (dialog.ShowDialog() == true)
{
    var targetFile = @"..\..\Images\" + name + ".png";
    var currentDir = Environment.CurrentDirectory;
    var targetPath = Path.Combine(currentDir, targetFile);
    var targetDir = Path.GetDirectoryName(targetPath);

    Directory.CreateDirectory(targetDir);

    File.Copy(dialog.FileName, targetPath, true);

    image.Source = new BitmapImage(new Uri(targetPath));
}

为了在加载BitmapImage后直接释放文件,从FileStream加载:

BitmapImage bitmap = new BitmapImage();

using (var stream = File.OpenRead(targetPath))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

image.Source = bitmap;