Skip to main content

Formatting strings in binding

Recently I get a chance for a code walk through of an WPF application in order to achieve better performance. So, during my review process, I came across this 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 get a way to optimize it. Well, I am talking  about formatting the string as well as binding part.

As most of you are aware that we have a property named StringFormat since .Net 3.5 SP1. So, why can't we use this StringFormat for our binding too. If you want to change the above code to incorporate StringFormat, then it will something look like:

<WrapPanel>
        <TextBlock>
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} {1}">
                        <Binding Path="FirstName" Mode="OneWay"/>
                        <Binding Path="LastName" Mode="OneWay"/>
                    </MultiBinding>
                </TextBlock.Text>
        </TextBlock>
    </WrapPanel>

Now here one can clearly see the double benefit of writing such code. First benefit is, instead of using two bindings, one can be used and another benefit is instead of using three TextBlocks only one TextBlock can be used.

This may help in achieving 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 XAML parser would consider { to be the beginning of markup extension.

Comments