I have been integrating image resources to my WPF assemblies for quite a time, but I never really found a really p开发者_如何学编程retty way of binding them in my MVVM applications.
So I was wondering if some you, stackoverflow users, could share their own practice when it comes to assembly ressources:
- How do you reference them in C#/VB and XAML?
- When exposing them from code, what type do you expose? (BitmapImage, Uri, string, ...)
- Do you prefer referencing them from the view or binding them through view-model?
- Do you use a specific assembly to store them? How do you organize them?
Thanks for your help ;-)
This is what I do...
- Images are kept in some folder such as
Images
in project's root folder. You can keep them in any assembly. - Individual image has
Build Action
property set toResource
type. The ViewModel holds image name in
string
(say propertyMyImageName
) and I convert it as a relative path when bound to theSource
ofImage
object in XAML...public class ImagePathConverter { public void Convert(...) { return "pack://application:,,,/MyApplicationName;component/Images/" + value.ToString(); } }
where MyApplicationName
is the short assembly's name that is having the Images
folder under it.
In XAML, assuming the view model instance is bound to the data context of the entire view and / or atleast to the image's data contect ....
<Image Source="{Binding Path=MyImageName, Converter={StaticResource ImagePathConverter}}" />
But then thats one of the typical ways to refer images in a WPF project via MVVM. Other ways include an Image's binary stream loaded (from resx
or Content
type images or from binary database). In such case your converter will convert it into a BitMapImageSource
.
精彩评论