Find an image URI in a WPF program in C#


[image URI]

One of the more annoying changes introduced in WPF and XAML is the image URI. Now instead of simply selecting an file from a resource, you need to supply an arcane string such as:


pack://application:,,,/howto_wpf_learn_uri;component/csharp_prog_ref.png

It’s another case of WPF’s unofficial theme: Twice as flexible and only five times as hard.

With a little experience (okay, a lot of experience) you can learn how to create that kind of image URI, but there’s an easier way to find it. First add the image to the project by following these steps:

  1. Use Project > Add Existing Item to add the image file to the project.
  2. Select the file in Solution Explorer and verify that its Build Action property is set to Resource.
  3. Create an Image control and set its Source property to the name of the file as in csharp_prog_ref.png.

The Window Designer lets you set the Source property as a string, but it’s actually an object (a BitmapFrameDecode) and its ToString method returns the image’s URI. Now you can run the program and use the debugger or some other method to read that property’s value and get the URI.

This example uses the following code to display the URI in a TextBox at runtime.

// Display the Image control's URI.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    txtUri.Text = imgBook.Source.ToString();
}


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in files, wpf, XAML and tagged , , , , , , , , , . Bookmark the permalink.

One Response to Find an image URI in a WPF program in C#

Leave a Reply

Your email address will not be published. Required fields are marked *