Title: Find an image URI in a WPF program in C#
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:
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:
- Use Project > Add Existing Item to add the image file to the project.
- Select the file in Solution Explorer and verify that its Build Action property is set to Resource.
- 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 the example to experiment with it and to see additional details.