miércoles, julio 30, 2008

Value Converters - Databinding 101

This is the first of several posts related to Value Converts. Trying to minimize the length of the posts I break it in 4 deliveries, but the first one will have to be an intro to databinding before I can get into Value Converters tomorrow.

Databinding is great and probably one of the best features in WPF and SL (I know I have said that before for others), well, it's great, but somehow inflexible as we will see tomorrow and Value Converters will add a bit of flexibility.

As with winforms or ASP.NET to do databinding we will need a DataSource. We will define our person class.

public class Person
public string Name { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }

In our Codebehind we will add this to the DataContext property of the control

public partial class Page : UserControl

public Page()
DataContext = new Person {Name = "Miguel", LastName = "Madero", PhoneNumber = "+52 (871) 123-4567"};

Obviously in a real example we won't hard code the values and instead get our data from a Service. Then in XAML we will define the controls that will be bound to our object. In this case we're using only textboxes inside inside a StackPanel.

<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding LastName}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding PhoneNumber}" TextWrapping="Wrap"/>

That's it, super simple. There are obviously more complex examples, but I probably won't go there since other people have already have done a great job covering them, for example binding to a List Box (read Scott's post) or a DataGrid (all Scott Morris blog), or a step by step tutorial by Jesse Liberty who explains Binding objects, change notifications implenting INotifyPropertyChanged, Binding Modes (OneTime, OneWay, TwoWay). This is not an intro to databinding, rather an intro to Value Converters and why is it needed.

After a couple of modifications (see attached code) the page will look like this:


Everything looks as expected, so why would we need value converters. Imagines some people won't have phone numbers, we would be displaying a blank space, that might not be the desired experience. What if we want to show a default value like "Not available". Tomorrow we will see how to show default values using ValueConverters.

You can download the attached code here
I format my code using Manoli's website
Don't forget to vote for your favorite topics.

No hay comentarios.: