Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

Tip: Binding an Image element’s Source property to a Uri in WinRT XAML

Pete Brown - 27 March 2012

Over the years, I've conditioned myself to use the Uri class when surfacing web URLs in my application. Early versions of Silverlight couldn't bind an image source directly to an instance of a Uri because they lacked an appropriate type converter; the usual workaround was to change the property to a string type.

Subsequent versions Silverlight added that capability and the converter. For example. Given an instance of the following model class as the data context:

public class Tweet
{
public string Message { get; set; }
public Uri Image { get; set; }
}

In Silverlight, you can bind in XAML like this:


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

In the current version of Windows 8/WinRT XAML, you can't bind image sources directly to Uris, but there's a nice way to do it by using property element syntax and and a BitmapImage class. It's more verbose, but may be just the ticket if you need to bind to Uris and not strings, and can't change, or don't want to change, your [view]model.

<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Image}" />
</Image.Source>
</Image>

The team is aware of this difference, and have it in their backlog of things to prioritize for future revs. In case you're sharing markup or anything between WinRT XAML and Silverlight, it's good to know this more verbose approach works in both.

       
posted by Pete Brown on Tuesday, March 27, 2012
filed under:        

2 comments for “Tip: Binding an Image element’s Source property to a Uri in WinRT XAML”

Comment on this Post

Remember me