Alexandr
Alexandr

Reputation: 1901

Binding StringFormat and Converter together

I take user's avatar url from the web service (User.Avatar):

 /users/user_id/12?last_update=timestamp

In different controls I must use different size avatar (a web service can crop and resize image) :

 ImageSource="{Binding User.Avatar, StringFormat=http://myurl.com/\{0\}/crop/110x110, Converter={StaticResource ImageSizeUrlConverter}}"/>

Converter must take

http://myurl.com/users/user_id/12?last_update=timestamp/crop/110x110 (with StringFormat)

and return

http://myurl.com/users/user_id/12/crop/110x110?last_update=timestamp

But converter take /users/user_id/12?last_update=timestamp (without StringFormat).

This is normal behavior?

Upvotes: 4

Views: 5463

Answers (1)

Toni Petrina
Toni Petrina

Reputation: 7112

Well, it is supposed to be this way. You can bind any value to a string dependency property. Converter is used to convert from that type to target type. And since string formatting works only on strings, it makes no sense to act before the converter, only afterwords.

Here is an example:

{Binding SomeBoolValue,
         StringFormat=You said \{0\},
         Converter={StaticResource BoolToString}}

Where BoolToString returns "Yes" for true and "No for false. Formatting must take place after you convert the source type to the target type.

You can send the data as the ConverterParameter, but that cannot be bound to a static property. Your best solution would be to create an attached property here that does the binding and conversion.

Upvotes: 9

Related Questions