WP7–How to change an images source from code via a string property

Posted: 12/29/2011

When creating a custom Silverlight control you may want to enable a property that can be changed from binding, from straight XAML or via code. The following should allow you to do all of the above to change the source of an image in Silverlight for Windows Phone.

In the sub “OnSourceUriChanged” you see a direct cast to “ImageAnimation”. That should be the name of the control that you’re putting this property into. Mine happened to be ImageAnimation (which is a custom control I put together to reuse common Storyboards that I have created for use with images). Now that Mango is out the “Tap” event is exposed on images making them far easier to use (and more useful).

    Public Property Source() As String
         Get
             Return DirectCast(GetValue(SourceProperty), String)
         End Get
         Set(value As String)
             SetValue(SourceProperty, value)
         End Set
     End Property
  
  
    Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(String), GetType(ImageAnimation), New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnSourceUriChanged)))
  
  
    Private Shared Sub OnSourceUriChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
        DirectCast(d, ImageAnimation).OnSourceUriChanged(e)
    End Sub
  
  
    Protected Overridable Sub OnSourceUriChanged(e As DependencyPropertyChangedEventArgs)
         image.Source = New ImageSourceConverter().ConvertFromString(e.NewValue.ToString)
    End Sub