Click here to Skip to main content
12,747,154 members (29,306 online)
Click here to Skip to main content
Add your own
alternative version

Stats

4.2K views
3 bookmarked
Posted 14 Dec 2013

Formatting Strings in Binding

, 14 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How to format strings in binding

Introduction

Recently, I got a chance to do a code walk through of a WPF application in order to achieve better performance. So, during my review process, I came across the code snippet given below:

<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, we have a property named StringFormat since .NET 3.5 SP1. SO, why can't we use this property for our binding too. If you want to change the above code to incorporate StringFormat, then it will look something 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, once can clearly see the double benefit of writing such code. The first benefit is, instead of using two bindings, one can be used and another benefit is instead of using three TextBlocks, only one can be used.

This may help in achieving performance especially when used as a DataTemplate of an ItemsControl with a 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170215.1 | Last Updated 14 Dec 2013
Article Copyright 2013 by Shweta Lodha
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid