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

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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>

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:

Published at DZone with permission of Jevgeni Tšaikin. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}