Question

I ran into a special behavior when binding to the Source property of an Image, using a converter.

It appears that if I use a simple Binding with a IValueConverter that returns a string correpsonding to a relative path to the image, everything is OK and the image is displayed.

On the other hand, if I use a MultiBinding with a IMultiValueConverter that returns the same string, the binding doesn't work and this error message is displayed in VS2010 output window :

System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='' MultiBindingExpression:target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')

I found out that for this to work, I can't return a simple string (and not even a Uri). I instead have to create a ImageSource in my converter (a BitmapImage, in fact) and return it.

Do you know why this strange behavior happens? Is this a known difference between Binding and MultiBinding, or is it a bug?

I found another stackoverflow topic that may relate to this, where Alvin posted a comment about the time when the binding are resolved :

I think that MultiBinding is made AFTER TextBlock rendering, and (single)Binding BEFORE TextBlok rendering – Avlin

To Illustrate this problem, I wrote a small project that you can download and test.

Thanks for any insights!

Was it helpful?

Solution

I would assume that this is by design but to be sure you would need to ask one of the developers, the difference is just that no type conversion is applied to the values returned by MultiBindings, people trip on that fairly often.

OTHER TIPS

I've got this working as followed (simplified code !)

My XAML:

<MediaElement LoadedBehavior="Play" Stretch="UniformToFill">
    <MediaElement.Source>
        <MultiBinding Converter="{StaticResource ActionMedia_Converter}"> 
            <Binding Path="HomeW_Background_FileName" />
            <Binding Path="HomeW_Background_FileType" />
        </MultiBinding>
    </MediaElement.Source>
</MediaElement>

My converter :

Public Class ActionMedia_Converter
	Implements IMultiValueConverter

	Public Function Convert(values As Object(), TargetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
		Dim ImageSource As String

		ImageSource = String.Concat(values(0), ".", values(1))

		Dim MyUri = New System.Uri(ImageSource)
		
		Return MyUri

	End Function

	Public Function ConvertBack(values As Object, targetTypes As Type(), parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
		Return Binding.DoNothing
	End Function

End Class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top