Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Binding Image, Brush or Color to Background property in Silverlight and Windows Phone 7

DZone's Guide to

Binding Image, Brush or Color to Background property in Silverlight and Windows Phone 7

· Mobile Zone ·
Free Resource
I’ve decided to post a property I use to bind Image / Brush / Color hex to Background property of Silverlight or Windows Phone 7 control. First of all, do not use that property in every Background Binding case to avoid a minor loss of performance, use it in rare cases, when you have no other option. To bind image I am using ImageBrush, for Brush (with color) I am using SolidColorBrush and for Color hex – string.
public object CustomBackground
{
    get
    {
        if (...background should be an image...)
        {
            // bind Image
            return new ImageBrush
                   {
                       ImageSource = new BitmapImage(new Uri(..image url...))
                   };
        }
 
        if (...background should be a brush...)
        {
            // bind Brush
            return new SolidColorBrush(Colors.Blue);
        }
 
        // bind color hex (RGB hex or RGB+Alpha hex)
        return "#FFFFFFFF";
    }
}

You can bind this property to Background using standard approaches to Data Binding in Silverlight.


<Grid Background="{Binding CustomBackground}">
...
</Grid>
Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}