WPF image control source

2019-02-21 22:23发布

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?

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条回答
贪生不怕死
2楼-- · 2019-02-21 23:12

you'll need to change the File Name into a URI and then create a 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;
}
查看更多
别忘想泡老子
3楼-- · 2019-02-21 23:15
imagebox.Source = new BitmapImage(new Uri(openfile.FileName));
查看更多
放荡不羁爱自由
4楼-- · 2019-02-21 23:26

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

查看更多
登录 后发表回答