views:

284

answers:

1

I am trying to bind the Text of a TextBox named 'txtImage' to an image using the following code with no results:

<Image Source="{Binding ElementName=txtImage, Path=Text}" />

What would the right approach be?

A: 

Source of Image requires a BitmapImage, thus try using a Value Converter to convert the string to an Image:

public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        try
        {
            return new BitmapImage(new Uri((string)value));
        }
        catch 
        {
            return new BitmapImage();
        }
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}  

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding ElementName=txtImage, Path=Text, Converter=...}" />
    </Image.Source>
</Image>

Reference: http://stackoverflow.com/questions/20586/wpf-image-urisource-and-data-binding

Andreas Grech
In order for this to work, would the converter have to be decared in procedural code?
JP
The converter should be declared in the Resources section (in xaml). For example, in Window.Resources
Andreas Grech
Thank you very much.
JP