WPF图像控制源

时间:2009-08-06 20:19:34

标签: c# image wpf-controls

我试图重新创建一个非常简单的C#项目示例我是WPF,它是一个简单的图像查看器..来自山姆自学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 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分: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 :(得分:2)

您还可以将图像添加为资源,即添加现有项目并将图像的构建操作属性更改为资源

然后以这种方式引用它

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

((Image)sender).Source = bitImg;

这样你就不需要在程序中包含图像了,它作为资源捆绑到包中