A Windows Phone 7 behavior to show an image background for a search string


On New Year’s Eve I can’t help but writing this last bit of 2011: yesterday on a #wp7nl developer’s meet up, which was basically a free-for-all fun hacking event organized by Matthijs Hoekstra, I wrote a little thingy for Windows Phone 7 that accepts a string, tries to find an image for it using Bing Image search and displays it as a background. Of course it’s a behavior – I write behaviors a dozen, because the concept of reusable dynamic behavior is something that fits very well with the way I think. Call me the behaviornator if you like ;-)
It’s very simple, it’s quite fun, demonstrates at little Rx usage, makes quite unusual use the of Bing Image Search api - and it will play a supporting act in my newest Windows Phone 7 app. The basic structure of the behavior is set up utilizing the #wp7nl library SafeBehavior that I described earlier:
using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Phone.Reactive;
namespace Wp7nl.Behaviors
{
/// <summary>
/// A behavior that puts an image on the background of the Attched object
/// using Bing Image Search
/// </summary>
public class DynamicBackgroundBehavior : SafeBehavior<Panel>
{
private ImageBrush backgroundBrush;
public DynamicBackgroundBehavior()
{
Opacity = 1.0;
}
#region SearchString
public const string SearchStringPropertyName = "SearchString";
/// <summary>
/// The search string to be used on Bing Maps
/// </summary>
public string SearchString
{
get { return (string)GetValue(SearchStringProperty); }
set { SetValue(SearchStringProperty, value); }
}
public static readonly DependencyProperty SearchStringProperty =
DependencyProperty.Register(
SearchStringPropertyName,
typeof(string),
typeof(DynamicBackgroundBehavior),
new PropertyMetadata(String.Empty, SearchStringChanged));
public static void SearchStringChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var behavior = d as DynamicBackgroundBehavior;
if (behavior != null)
{
behavior.StartGetFirstImage((string)e.NewValue);
}
}
#endregion
/// <summary>
/// Bing search key
/// </summary>
public string BingSearchKey { get; set; }
/// <summary>
/// Stretch used for the image
/// </summary>
public Stretch Stretch { get; set; }
/// <summary>
/// Opacity used for the image
/// </summary>
public double Opacity { get; set; }
}
}
In short, this behavior has four properties:
- Opacity
- Stretch
- BingSearchKey
- SearchString