Reputation: 187
I have a DataGrid
that gets binded by various DataTable
s. The nullable boolean
columns get converted into DataGridCheckboxColumn
. is there a way to convert this to a text column that shows yes, no, not available?
Upvotes: 0
Views: 39
Reputation: 818
If you wanna keep the auto generating behavior you can subscribe to the AutoGeneratingColumn
event from the DataGrid
and change the generated DataGridColumn
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column is DataGridCheckBoxColumn dataGridCheckBoxColumn)
{
Binding binding = (Binding)dataGridCheckBoxColumn.Binding;
binding.Converter = new BooleanToStringConverter(); //Converter Klaus Gütter mentioned
e.Column = new DataGridTextColumn()
{
Header = dataGridCheckBoxColumn.Header,
Binding = binding
};
}
}
Upvotes: 1
Reputation: 12007
You could craete a value converter and specify it the binding as Converter.
public class BooleanToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType == typeof(string) && value is bool?)
{
var b = (bool?)value;
if (!b.HasValue)
return "not available";
return b.Value ? "yes" : "no";
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// implement it if you need two-way binding
throw new NotImpementedException();
}
}
In XML, create an instance of it in the Resources
<local:BooleanToStringConverter x:Key="BooleanToStringConverter" />
and add it to the binding
Binding={"Binding MyColumn, Converter={StaticResource BooleanToStringConverter}}"
Upvotes: 1