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?
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", ""));
}
}
This is quite an old question, but I think this is the current best solution (if you want to edit the text).
You can do it with an InlineUIContainer
in a TextBlock
with a nested Textbox
.
Note: I've used BaselineAlignment="Center"
to align the components. You can also add positive or negative margins to the TextBox
as necessary. Also I set the border of the TextBox
as transparent to make it look like part of the TextBlock
even though it is editable and selectable.
<TextBlock Foreground="SteelBlue">
<Run Text="Package Barcode:" FontWeight="Bold" BaselineAlignment="Center"/>
<InlineUIContainer BaselineAlignment="Center">
<TextBox Margin="2,0,0,0" Foreground="Gray" Text="{Binding BarcodeNumber}" BorderThickness="0" Padding="0"/>
</InlineUIContainer>
</TextBlock>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With