I’m trying to allow for multiple icon sizes depending on certain conditions. To do this, I have a bunch folders: ‘Images\Icons\…\*.png’ where the … is the size (16, 32, 64, 128, 256, etc.) Each folder contains all the icons optimized for the given size.
My problem I can’t seem to specify a folder in the image source path… i.e.:
<Image x:Name = "img"
Stretch = "None"
Source = "{Binding StringFormat=Images\Icons\{0}\Multi.png,
RelativeSource={RelativeSource Self},
Path=Parent.Parent.Tag}" />
For now, I’m just storing the folder name in the grandparent’s tag (I will be binding to something else in the future, but right now I’m just trying to piece this bit together). When I try to build the above xaml, I get an error:
The text \Multi.png ... is not allowed after the closing } of a markup extension.
This leads me to beleave that it’s seeing the {0} as a markup extension instead of it being a part of my string format. I’ve read about escaping with {} and using single quotes to specify the string format, but neither works:
Source = "{Binding StringFormat={}Images\Icons\{0}\Multi.png, ...
The above returns the same error as when I don’t escape at all..
Source = "{Binding StringFormat='Images\Icons\{0}\Multi.png', ...
Source = "{Binding StringFormat='{}Images\Icons\{0}\Multi.png', ...
The above two prevents the error from occurring, but results in the image source being null.
Does anyone know how to acheive this?
(Just to clarify, if the grandparent’s tag is set to ’16’, then I want the image source bound to Images\Icons\16\Multi.png … If the tag is set to ’32’ then I need to bind the source to Images\Icons\32\Multi.png. As a test, I set the grandparents tag to the full path, and excluded the stringformat. The relative binding to the grandparents tag succeeded and the image was shown. It only fails when I try to specify just the folder name with a stringformat to specify the rest of the path).
The StringFormatter attribute of Binding will only work if the target is of type String. Otherwise, it will simply be ignored.
You can fix this by adding a converter to your binding, which takes the format string and your tag, applies the formatting, and converts it to an ImageSource. In C#, your converter will look something like:
Once you’ve got your converter, you can add the following to your Resources in XAML:
And modify your Source binding to: