I have a data collection that I'd like to display in a WPF DataGrid (in C#). Setting the ItemSource property of the DataGrid works great. The control grabs values, places them in columns and generally just works. The problem is that some of the attributes in the displayed object are IDs. For editing, that's fine, but for displaying them on screen I want to return the string to which they correspond.
In other words, instead of:
I want:
In Qt, there's a concept of "role" for the ::data() method. How do I hand the appropriate "version" of a particular field to the DataGrid?
You can use IValueConverter to convert 'Box type' integer to string like this:
class BoxTypeConverter : IValueConverter
{
private static readonly List<string> idNames = new List<string>()
{
"Flat-rate (small)",
"Flat-rate (medium)",
"Flat-rate (large)",
"Regional A",
"Regional B",
"Regional C"
};
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var index = (int)value - 1;
return index >= 0 && index < idNames.Count ? idNames[index] : value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var idName = (string)value;
var index = idNames.IndexOf(idName);
return index >= 0 ? index + 1 : int.Parse(idName, culture);
}
}
And hook it up into DataGrid like this:
XAML
<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"/>
C# behind XAML
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "BoxType")
{
var column = (DataGridBoundColumn)e.Column;
var binding = (Binding)column.Binding;
binding.Converter = new BoxTypeConverter();
}
}