开发者

Providing the WPF designer with an image at DesignTime

This is a restatement of my question, the revision history contains the original mess.

What it boils down to is "How do I get the application's directory from my WPF application, at design time?"

Which duplicates the question here so if you happen to be passing by please vot开发者_开发技巧e to close, thanks.


Do you need the image to be "Content - Copy if newer"? If you switch it to "Resource" you can use the following path to reference the file:

"/MyImage.JPG"

or a longer version

"pack://application:,,,/MyImage.JPG"

given that the image is in the root of the project, otherwise just change the URI to

"/Some/Path/MyImage.JPG"

UPDATE 1:

For me, the longer pack uri syntax works with an image marked as "Content - Copy if newer" as well. However, the shorter syntax does not work. I.e:

This works:

"pack://application:,,,/MyImage.JPG"

This does NOT work:

"/MyImage.JPG"

I my example I added the image to the root of the project, and marked it as "Content". I then bound the design time data context to a view model with a property returning the longer pack URI above. Doing that results in the Content image being shown correctly at design time.

UPDATE 2:

If you want to load a bitmap source from a pack uri, you can do so by using another overload of the BitmapFrame.Create which takes an URI as the first parameter.

If I understand your problem correctly you get the string with the pack uri as the first item in the object array that is passed to your converter. From this string you want to load a BitmapSource.

Since the string contains a pack URI, you can create an actual URI from the string and then use that URI to load the BitmapSource:

var imagePath = values[0] as string;
// ...
try
{
    var packUri = new Uri(imagePath);

        BitmapSource bitmap = BitmapFrame.Create(packUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        {
            // ...
        }
    }
}


Just return the exact path of the image from your entity in ImagePath property, such as ..

"C:\MyImage.JPG"

..

OR

..

"C:\MyApp\bin\Debug\MyImage.JPG"

Then your binding (i.e. <Image Source="{Binding ImagePath}" />) in .xaml will start working..


I solved it by leveraging the clevers found in this stackoverflow answer.

public class DMyViewModel : PhotoViewModelBase
{
    public override string ImagePath
    {
        get
        {
            string applicationDirectory =
                (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                 where assembly.CodeBase.EndsWith(".exe")
                 select System.IO.Path.GetDirectoryName(assembly.CodeBase.Replace("file:///", ""))
                 ).FirstOrDefault();
            return applicationDirectory + "\\MyImage.JPG";
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜