Search code examples
c#xamlwindows-phone

Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?


To bind a value to a TextBlock we use the following syntax to display an <ItemName> property of a bounded object.

<TextBlock Text="{Binding Path=ItemName}" />

But is there a syntax to use the above tag to concatenate the constant string 'Item' with the databounded property, in order display something like: Item <ItemName> in the TextBlock


Solution

  • You can use a StringFormat in your binding, like so:

    <TextBox Text="{Binding ItemName, StringFormat={}Item: {0}}"/>
    

    That being said, it may cause some unexpected behavior when editing. For example, if the user edits only the item name (excluding the 'Item:' text), then when the TextBox loses focus, the string format will be displayed as "Item: Item: xyz", which is a bit weird. There might be a way to get around this issue, but nothing that springs to mind right now.

    However, if the user clears the entire TextBox, then sets the name, then that's all fine and dandy.

    Otherwise, it would probably be a better idea to use a TextBlock in front of your TextBox. Like so:

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Item:" VerticalAlignment="Center"
                   Margin="0,0,6,0"/>
        <TextBox Text="{Binding ItemName}"/>
    </StackPanel>