At design time pack uri is valid, but not at runtime?

后端 未结 4 1420
暖寄归人
暖寄归人 2021-02-13 19:00

I\'m setting a Button\'s content to an Image. It looks something like this:

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 19:39

    I just struggled with this same problem for quite a while, and I think that part of what was going wrong in the original was the missing word "component". I, for instance, had

    myBitmapImage.UriSource = new Uri(@"pack://application:,,,/MyApp;images/mona2.jpg");
    

    but should have had

    ... = new Uri(@"pack://application:,,,/MyApp;component/images/mona2.jpg");
    

    The word "component" is not part of the pathname, despite its appearance -- it's a string literal that has to be there. Why? Someone thought it'd be a good idea, I guess.

    And for those struggling with another part of the thing, what about "MyApp"? That's the name of the Assembly. Right-click on your project name, select "Properties...", and under the "Application" tab you'll see the "Assembly name:" field.

    If you don't feel like searching for that (or worry that it might change, breaking your code), you can do this:

    String appUri = @"pack://application:,,,/" + 
                      System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ";";
    String path = appUri + "component/images/mona2.jpg";
    myBitmapImage.UriSource = new Uri(path);
    

    Not very pretty code, I admit -- it can clearly be shortened -- but it'll gets you where you need to go, I hope. Remember to set the "Build" property on your image file to "Resource"!

提交回复
热议问题