We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
When working with WPF I always found myself thinking how to handle Data formatting when a WPF control was bound to it. Let’s look at the following example of a window with a TextBlock that displays a DateTime:
And the code behind:
The outcome is this:
But what if we wanted to change the format of the DateTime? Before .NET 3.5 SP1 we had 2 options:
That was the easiest and fastest way to make the data in the UI formatted in the way you wanted let’s say we wanted the DateTime to display like this: 11:49 2/5/2009, we would have done this:
and have the UI bind to the Now property:
The outcome is what we wanted:
I don’t like this way of work for 2 reasons:
This is a much better way of work because it solves the 2 problems I had with the Property method of formatting data. Using a converter keeps UI logic in the UI, removes the clutter from the code behind and is reusable.
Here is how we do it:
First we add the converter:
Use it with the binding:
And have the DataContext be DateTime.Now:
And the outcome? Just as before:
The only drawback to this method is that it is takes more effort.
But we just got lucky..
In .NET 3.5 SP1 we got the StringFormat option in Binding!
This makes things so much easier All we have to do is have the Binding Expression look like this:
And that’s it, no extra Properties and ValueConverters.
I could have copied the image again but trust me it gives the same outcome in a much more elegant way.
Do you have a different way of work? let me know.
Tags :.NET 3.5 SP1BindingpropertyString.FormatValueConverterWPF
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd