0
votes

When I am working on a button template I just encountered a binding StringFormat issue. Here it is.

-- I setup a button with a given ToolTip as a string. I like to use it to specify the image name within binding. Then I apply it to a button style called ImageButton.

<Button ToolTip="Minimize" Height="34" Style="{StaticResource ImageButton}"  Margin="220,36,125,371" />;

-- This is the code in style. I like to use the image name from the binding and come up with a full image path. It is supposed to be working like this, <Image x:Name="ButtonImage" Source="Images/Minimize-Normal.png" />. Yes, I do have such a image in place and it works great if I just put the xml code without binding.

<Image x:Name="ButtonImage" Source="{Binding ToolTip, RelativeSource={RelativeSource TemplatedParent}, StringFormat={}Images/{0}-Normal.png}" />

But the binding did not work as I expected. The image cannot be shown correctly. If I put the Image full name in ToolTip then it worked correct. It looks like the StringFormat had been ignored.

Any help will be appreciated. Thanks in advance.


Thanks for dbaseman's response. I know I can achieve it by using Converter. But as I think StringFormat is easier to apply, that's why I tried this.

I also found a reply here, it says - StringFormat is used when binding to a string property, while the Text property in your control is of type object, hence StringFormat is ignored.


It should be by design. Below code works. Because the Text property is string type.

<TextBlock Text="{Binding ToolTip, RelativeSource={RelativeSource Self}, StringFormat={}Images/{0}-Normal.png}" ToolTip="Minimize" />
1

1 Answers

0
votes

That's interesting -- I'm not sure if it's a bug, or by design. You can work around this problem, though, by using a Converter instead of StringFormat.

public class ImageNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("Images/{0}-Normal.png", value);
    }

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

And then of course:

<local:ImageNameConverter x:Key="ImageNameConverter" />

And:

<Image x:Name="ButtonImage" 
    Source="{Binding ToolTip, 
                RelativeSource={RelativeSource TemplatedParent}, 
                Converter="{StaticResource ImageNameConverter}}" />

Edit I think it's by design. From the docs for BindingBase.StringFormat:

Gets or sets a string that specifies how to format the binding if it displays the bound value as a string.

So (apparently) the string-format conversion won't happen unless the binding source is to actually be rendered as a text string.