我有一个DataGrid
被各种DataTable
绑定。可为空的boolean
列将转换为DataGridCheckboxColumn
。有没有一种方法可以将其转换为显示是,否,不可用的文本列?
答案 0 :(得分:1)
您可以创建一个值转换器,并将其绑定指定为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();
}
}
在XML中,在参考资料中创建它的一个实例
<local:BooleanToStringConverter x:Key="BooleanToStringConverter" />
并将其添加到绑定中
Binding={"Binding MyColumn, Converter={StaticResource BooleanToStringConverter}}"
答案 1 :(得分:1)
如果要保留自动生成行为,可以从AutoGeneratingColumn
订阅DataGrid
事件并更改生成的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
};
}
}