开发者

binding an image source in XAML

I am trying to bind an image source to my XAML through c#

this works

<Image Source="i开发者_高级运维mages/man.jpg"></Image>

this does not work

<Image Source="images/{Binding imagesource}"></Image>

where imagesource is a string variable in the c# file of this xaml and is being set equal to "man.jpg"


here is a way how to do it in XAML:

add this to the namespace:

xmlns:System="clr-namespace:System;assembly=mscorlib"

then add your images paths

<System:String x:Key="ImageRefresh">/Theme;component/Images/icon_refresh.png</System:String>
<System:String x:Key="ImageSearch">/Theme;component/Images/icon_search.png</System:String>

This is how you use it

<Image Height="16" Source="{StaticResource ImageSearch}" Stretch="Uniform" Width="16"/>

This works ok, but if you load your xaml style in Blend it will go bogus..

An object of type "System.String" cannot be applied to a property that expects the type "System.Windows.Media.ImageSource".

I haven't figured out yet, how to replace System:String with that Media.ImageSource... but hey.. it works for me in Visual Studio.


You can't stick a binding mid-way through the value like that. It's either a binding, or it's not. Assuming imagesource is publicly accessible via your DataContext, you could do this:

<Image Source="{Binding imagesource}"/>

However, if it's been set to "man.jpg" then it won't find the image. Either set imagesource to the full path ("images/man.jpg") or use a converter:

<Image Source="{Binding imagesource, Converter={StaticResource RelativePathConverter}}"/>

The converter would prepend "images/" onto its value. However, it may be necessary for the converter to return an ImageSource rather than a string.


Images have bitten me in the past. There is a certain lookup order involved.

When you use "image/man.jpg" it could refer to a file inside your silverlight xap, or relative to the location of XAP file. For example, it could be in YourProject.Web/ClientBin/image/man.jpg.

You should troubleshoot by using full URLs first and find out if this works.


imagesource needs to be an actual Image object, not a string.

Here is a method that will create a new Image object given a path:

public BitmapImage Load(string path)
{
    var uri = new Uri(path);
    return new BitmapImage(uri);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜