Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Alexandr Avatar asked Feb 15 '23 02:02

Alexandr


1 Answers

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.

like image 57
Toni Petrina Avatar answered Feb 19 '23 21:02

Toni Petrina