WPF指定在绑定列时如何生成列

时间:2018-11-30 22:51:42

标签: c# wpf

我有一个DataGrid被各种DataTable绑定。可为空的boolean列将转换为DataGridCheckboxColumn。有没有一种方法可以将其转换为显示是,否,不可用的文本列?

2 个答案:

答案 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
        };
    }
}