Concatenate/Format Strings in XAML
Often, you will need to put dynamically concatenated strings on the screen. By this, I mean strings that are built at runtime by concatenating several static and non-static substrings. Something you would do in code as follows:
string formattedString = FirstName + " " + LastName; // This is better performance-wise since a StringBuilder will be used internally, which means less objects will be created. string betterFormattedString = string.Format("{0} {1}", FirstName, LastName);
To do this in XAML, you can take the naive approach below.
<StackPanel Orientation="Horizontal"/> <TextBlock Text="{Binding Name}"/> <TextBlock Text=" "/> <TextBlock Text="{Binding LastName}"/> </StackPanel>
In this example, four UI elements are created: one StackPanel and three TextBlocks. This will have a performance impact since all these elements will need to go through a measurement and layout pass. In case this structure is used once or just a few times, you won’t notice this. However, if it is used in a datatemplate for use inside a list with many elements, you will notice a performance hit.
A better way to concatenate strings in XAML is shown below.
<TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1}"> <Binding Path="Name"/> <Binding Path="LastName"/> </MultiBinding> </TextBlock.Text> </TextBlock>
In this case, we only create one UI element instead of four! Not only is this better performance-wise, it is also much more readable.
Excellent tip – thanks for sharing.