views:

215

answers:

2

I have the following code to display a clients age.

<TextBox x:Name="txtClientAge" Text="{Binding Path=ClientAge}" />

However, instead of just displaying just the number, I want to prefix it with the text "Age " and suffix it with the text " yrs" so it is effectively becomes "Age 36 yrs"

I can achieve this with a horizontal StackPanel and 3 Textboxes, but is there a much simpler method that I'm missing?

+2  A: 

You could create a property in the class you're binding too that creates the text string you'd like to display.

There's also the StringFormat route:

<textblock text="{Binding Path=mydate, StringFormat=d}"/>

You can hack constants into the formatting string.

I prefer the property method.

Jay
This is essentially modifying your model to be view-aware - a very bad idea from design perspective.
Pavel Minaev
+1 for StringFormat. Agree with @Pavel - don't create a property with this text in it.
Andy
If you really want to do this right then the text doesn't belong in the view either. It needs to be in a resource area selected by the presentation layer based on your current culture setting. Which is why all my stuff comes from presenter properties.
Jay
+2  A: 

Assuming you don't need the age value to be editable, in WPF 4.0 the Text property of Run will be bindable, this probably doesn't help you right now unless you are using the pre-release but you will be able to do something like the following:

<TextBlock x:Name="txtClientAge" >
    <Run Text="Age "/><Run Text="{Binding Path=ClientAge}"/><Run Text=" Yrs"/>
</TextBlock>

UPDATE Heres another alternative to the format string solution that will work but is not particularly pretty (in fact its quite hacky). Use the following converter on the binding (assuming ClientAge property is of type int):

public class AgeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                          System.Globalization.CultureInfo culture)
    {
        string age = value.ToString();
        return "Age " + age + " years";
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture)
    {
        string age = value as string;
        return Int32.Parse(age.Replace("Age ", " ").Replace(" years", ""));
    }
}
Simon Fox
Thanks Simon, that was the sort of thing I was looking for but as you say, it's not quite with us yet! I might have to adopt a long winded approach for now until WPF 4.0 is with us.
Mitch
Nice bit of lateral thinking mate. I'm currently enjoying using Converters for all sorts of things so your approach really appeals. Thanks for that!
Mitch
Yeah the ConvertBack is the part I don't like, but since its a readonly situation that is not going to be a problem.
Simon Fox