Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF image control source

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;
     }
}
like image 788
Dabiddo Avatar asked Aug 06 '09 20:08

Dabiddo


People also ask

How do I use resource image in WPF XAML?

There is a slight variation on this: <Image Source="/Icons/play_small. png" /> Note the forward slash at the start which means look in the root folder. If the xaml file is not at the root, this is necessary as without the forward slash, it will start the search in the same directory as the xaml file.

How do you change the source of an image in UWP?

Here's how to set the source to an image from the app package. Image img = new Image(); BitmapImage bitmapImage = new BitmapImage(); Uri uri = new Uri("ms-appx:///Assets/Logo.png"); bitmapImage. UriSource = uri; img. Source = bitmapImage; // OR Image img = new Image(); img.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


2 Answers

imagebox.Source = new BitmapImage(new Uri(openfile.FileName));
like image 122
Charlie Avatar answered Oct 19 '22 04:10

Charlie


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;
}
like image 3
Stephen Wrighton Avatar answered Oct 19 '22 05:10

Stephen Wrighton