views:

1110

answers:

2

I have learned how to format strings in the content attribute of a label like this:

<Label Content="{Binding ElementName=theSlider, Path=Value}" 
   ContentStringFormat="The font size is {0}."/>

I want to do the same thing in a Setter but "ValueStringFormat" doesn't exist, what is the correct syntax to do what I want to accomplish here:

<DataTrigger Binding="{Binding Path=Kind}" Value="Task">
    <Setter TargetName="TheTitle" Property="Text" 
       Value="{Binding Title}" 
       ValueStringFormat="Your title was: {0}"/>
</DataTrigger>
+1  A: 

I can't test this but hope it works:

...
xmlns:local="clr-namespace:ValueConverter"
...

<Window.Resources>
   <local:MyTextConverter x:Key="MyTextConverter" />
</Window.Resources>

...
<DataTrigger Value="Task">
     <DataTrigger.Binding>
        <Binding Converter="{StaticResource MyTextConverter}"
            Path="Kind" />
     </DataTrigger.Binding>
     <Setter TargetName="TheTitle" Property="Text"/>
</DataTrigger>

where MyTextConverter is a class implementing IValueConverter interface:

public class PositionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
         CultureInfo culture)
    {
        return String.Format("Your title was: {0}", value);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
Stefano Driussi
This works, but you're taking away the ability of the designer to set the format string.
Will
+2  A: 

Can you simply use the StringFormat property of the Binding itself?

<DataTrigger Binding="{Binding Path=Kind}" Value="Task">
    <Setter TargetName="TheTitle" Property="Text" 
        Value="{Binding Title,StringFormat='Your title was: {}{0}'}" 
        />
</DataTrigger>
Matt Hamilton
+1, but shouldn't {0} be escaped with 2 curly braces - {} ?
arconaut
Indeed! I'll fix it now.
Matt Hamilton