Converter inside WPF autogenerated DataGridCell

It is amazing how fast you can show data in a WPF Datagrid, and is very useful the standard way it work. I have added a few lines (not as I see in the internet) in order to convert or hide colums and add converters in code-behind.


DG1.AutoGeneratingColumn += (s,e)=> {
List<String> properties = new List<string>() { "Date","Desription","AssignedID","Limit","Waiting"};
//Hiding several properties
properties.ForEach(p =>{ if(e.PropertyName == p) {e.Cancel = true;  return; }});
//Change the header
if (e.PropertyName == "FLimite")
e.Column.Header = "Limite";
}

Now let’s add a converter for an explicit column. In my case I have a column with an Int32 ID and I want to show the person name, so:


else if (e.PropertyName == "ID")
{
((Binding)((DataGridTextColumn)e.Column).Binding).Converter = UConverter;
}

where UConverter (my first time using convert to and back)  is an Instance of:


public class UserConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Int32 idx = (Int32)value;
return App.Users.First(u => u.ID == idx).Name;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
String name = (String)value;
return App.Users.First(u => u.Name== name).ID;
}
}

It is very useful in many cases, and avoids me to create extra properties and overload the classes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s