For almost each and every application the performance matters a lot, and most of the times it depends upon how the application has been designed and how the UI controls are being used. It’s not 100% possible to tune the performance and make the application perfect because many a times we are dependent on the external libraries and components for our application to be a functional one. Despite this, we can encourage its performance, as much as possible, by small tweaks, and here, I am going to discuss one such small tweaking tip for an XAML based app.
Let’s have a look at the below code snippet:
<WrapPanel>
<TextBlock Text="{Binding Path=FirstName,Mode=OneWay}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding Path=LastName,Mode=OneWay}"/>
</WrapPanel>
If you will closely analyze this given snippet, you will definitely find a way to optimize it. Well, I am talking about both, formatting the string as well as the binding part. As most of you are aware of the fact that we have a property named StringFormat since .Net 3.5 SP1, then why don’t we use this StringFormat for our binding too. Now, if you want to change the above code to incorporate the StringFormat, then it will look something like this:
<WrapPanel>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstName" Mode="OneWay"/>
<Binding Path="LastName" Mode="OneWay"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</WrapPanel>
Here one can clearly see the double benefits of writing such a code. The first benefit is, instead of using two bindings, one can be used and the other benefit is, instead of using three TextBlocks only one TextBlock can be used. This may help in achieving the performance, especially when used as a DataTemplate of an ItemsControl with huge number of items. Please note that {} part at the beginning is an escape sequence, otherwise the XAML parser would consider { to be the beginning of the markup extension.