WPF图像控件源

10

我试图在WPF中重新创建一个非常简单的C#项目示例,它是一个简单的图像查看器。从"Sams Teach Yourself C#"中,我已经成功打开了文件对话框,但如何将图像路径设置为WPF中的image.source控件呢?

private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
     Microsoft.Win32.OpenFileDialog openfile = new Microsoft.Win32.OpenFileDialog();
     openfile.DefaultExt = "*.jpg";
     openfile.Filter = "Image Files|*.jpg";
     Nullable<bool> result = openfile.ShowDialog();
     if (result == true)
     {
       //imagebox.Source = openfile.FileName;
     }
}
3个回答

21
imagebox.Source = new BitmapImage(new Uri(openfile.FileName));

谢谢,如何设置Sizemode.zoom属性? - Dabiddo

3
你需要将文件名更改为URI,然后创建一个BitmapImage。
if (File.Exists(openfile.FileName))
{
 // Create image element to set as icon on the menu element
 BitmapImage bmImage = new BitmapImage();
 bmImage.BeginInit();
 bmImage.UriSource = new Uri(openfile.FileName, UriKind.Absolute);
 bmImage.EndInit();
 // imagebox.Source = bmImage;
}

2

您还可以把图像作为资源添加,即添加现有项目并将图像的“生成操作”属性更改为“资源”。

然后可以用以下方式引用它:

BitmapImage bitImg = new BitmapImage();
bitImg.BeginInit();
bitImg.UriSource = new Uri("./Resource/Images/Bar1.png", UriKind.Relative);
bitImg.EndInit();

((Image)sender).Source = bitImg;

这样一来,您就不需要在程序中包含图像,它作为资源捆绑到包中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接