Wednesday, March 30, 2011

How to format string in XAML Setter Value?

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>
From stackoverflow
  • 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.");
        }
    
    Will : This works, but you're taking away the ability of the designer to set the format string.
  • 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>
    
    arconaut : +1, but shouldn't {0} be escaped with 2 curly braces - {} ?
    Matt Hamilton : Indeed! I'll fix it now.

0 comments:

Post a Comment