Home
Manage Your Code
Snippet: Get Image From Resource (WPF) (C#)
Title: Get Image From Resource (WPF) Language: C#
Description: This describe how to get image from resource file and shows usage Views: 109
Author: Nesim TUNÇ Date Added: 8/5/2008
Copy Code  
1  public static T loadResource<T>(string path)
2        {
3            T c = default(T);
4            StreamResourceInfo sri = Application.GetResourceStream(new Uri(path, UriKind.Relative));
5
6            if (sri.ContentType == "application/xaml+xml")
7                c = (T)XamlReader.Load(sri.Stream);
8            else if (sri.ContentType.IndexOf("image") >= 0)
9            {
10                BitmapImage bi = new BitmapImage();
11                bi.BeginInit();
12                bi.StreamSource = sri.Stream;
13                bi.EndInit();
14
15                if (typeof(T) == typeof(ImageSource))
16                    c = (T)((object)bi);
17                else if (typeof(T) == typeof(Image))
18                {
19                    Image img = new Image();
20                    img.Source = bi;
21                    c = (T)((object)img);
22                }
23            }
24            sri.Stream.Close();
25            sri.Stream.Dispose();
26            return c;
27        }
Usage
((Image)((DockPanel)btnHandUpDown.Content).Children[0]).Source = General.loadResource("Resources/fingerUp.png"); ;