views:

98

answers:

3

Hopefully I phrased the question correctly. If not, let me explain. I want to bind an Image element's Source property to a the ImageUrl property of my DataContext object. Here is the XAML:

<Image
    x:Name="EmployeeImage"
    Grid.Column="0"
    Grid.Row="0"
    Grid.RowSpan="2"
    Source="{Binding Path=ImageUrl}"
    Stretch="UniformToFill">
</Image>

Obviously I can just perform the binding in code-behind and perform any checks there, but is there a way to declaratively provide an alternative Url for the image source if the ImageUrl property is null or empty?

Edit: I added a converter which checks the ImageUrl and returns a default path if it is null or empty. If there is another way, I'm interested to hear it.

Thanks!

+1  A: 

Why not just have the object that you are binding to handle it?

public string ImageURL
{
  get { return (_ImageURL != string.Empty) ? _ImageURL : _MyDefaultImageURL; }
}
Charles Graham
I'm binding to a class that is auto-generated from a service reference. I guess I could create a matching partial class that exposes a new property that does this funtionality, e.g. public string ValidatedImageUrl { ... }. Thanks for the suggestion!
Kevin Babcock
+1  A: 

There is a way you can do it declaratively but you will need to write a class that derives from IValueConverter first. Once you've done that you can use that class to do any checks to get called when the Path binding is activated.

XAML Example:

<Image Source="{Binding Path=ImageUrl, Converter={StaticResource YourImagePathConverter}}"/>
sipwiz
This is the route I went with. Thanks for the suggestion!
Kevin Babcock
A: 

Source="{Binding Path=ImageUrl, FallbackValue=DefaultPathHere}" works in WPF, not sure if FallbackValue works in Silverlight.

http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.fallbackvalue.aspx

A little research suggests FallbackValue is available in Silverlight 4, but not previous version.

Turntwo