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

问题描述 投票:0回答:1

我正在尝试将所选图像复制到文件夹,然后要与Image对象一起显示。复制工作正常,但是当我要显示它时,似乎程序找不到它。仅当我手动使用“添加现有项”时,才显示图像。有没有办法自动添加它?

这是我的代码:

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));
}

(“图像”在xaml中定义)

c# wpf image bitmapimage filedialog
1个回答
1
投票

使用绝对路径加载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;
© www.soinside.com 2019 - 2024. All rights reserved.