C# WPF图片控件源码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1241156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:05:05  来源:igfitidea点击:

WPF image control source

c#imagewpf-controls

提问by Dabiddo

im trying to recreate a very simple example of a C# project i WPF, its a simple image viewer.. from the sam's teach yourself C#, ive managed to get the open file dialog to open, but how do i set the image path to the image.source control in WPF?

我试图重新创建一个非常简单的 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;
     }
}

采纳答案by Charlie

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

回答by Stephen Wrighton

you'll need to change the File Name into a URI and then create a bitmapimage

您需要将文件名更改为 URI,然后创建位图图像

:

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

回答by PrimeTSS

You can also add the image as a resource, ie Add Existing item and change the image's Build Action property to Resource

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

then reference it this way

然后以这种方式引用它

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

((Image)sender).Source = bitImg;

This way you dont need to include the image with the program, its bundled into the package as a resource

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