Joezer
Joezer

Reputation: 675

Resource image can be referenced in Xaml but not in code, why?

Excuse the novice question, but I am just learning WPF. I have an image that I've set the build action to be "Resource"

If I set it as the Window Icon in the XAML it works just fine. like this:

Window ... Icon="Images/MyIco.png"

But, if I try to set it as the source for an Image, I get an exception the resource is not found:

Uri uri = new Uri("pack://application:,,,/Images/MyIco.png"); // This does not work
img.Source = BitmapFrame.Create(uri); 

What am I doing wrong in the code above?

Upvotes: 0

Views: 128

Answers (1)

Thanh Le
Thanh Le

Reputation: 773

Make sure your path is correct, if true, u can try this code to load your image

    //tmp is your path
    BitmapImage img = new BitmapImage(new Uri(tmp, UriKind.Relative));
    img.CreateOptions = BitmapCreateOptions.None;
    img.ImageOpened += img_ImageOpened;

    void img_ImageOpened(object sender, RoutedEventArgs e)
    {
        WriteableBitmap wbm = new WriteableBitmap((BitmapImage)sender);                
    }

Ex: my path is "/Assets/sizes/background/bg_02.png"

Upvotes: 1

Related Questions