当 AutoGenerateColumns for nullable bool 时,WPF DataGrid 强制绑定 DataGridCheckBoxColumn [英] WPF DataGrid force binding DataGridCheckBoxColumn when AutoGenerateColumns for nullable bool

查看:34
本文介绍了当 AutoGenerateColumns for nullable bool 时,WPF DataGrid 强制绑定 DataGridCheckBoxColumn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有很多带有动态数据绑定的DataGrid,所以我们总是使用AutoGenerateColumns=True.对于 bool 列生成 DataGridCheckBoxColumn 但对于可为 null 的 bool(bool? 在 C# 中)生成默认的 DataGridTextColumn.有什么方法可以强制 DataGrid 自动为可空 bool 生成 DataGridCheckBoxColumn 吗?不喜欢依赖于实现的黑客.一些代码隐藏也被接受,例如在 AutoGeneratingColumn 事件中.

We have lots of DataGrid with dynamic data binding, so we always use AutoGenerateColumns=True. For bool columns generates a DataGridCheckBoxColumn but for a nullable bool (bool? in C#) generates the default DataGridTextColumn. Is there any way to force the DataGrid generate automatically a DataGridCheckBoxColumn for nullable bool? Prefer not implementation-dependant hacks. Also some code-behind is accepted for example in the AutoGeneratingColumnevent.

推荐答案

您应该注册 AutoGeneratingColumn 事件并根据列类型更改生成的列,如下所示:

you should register to AutoGeneratingColumn event and change the generated column based on column type, like so:

  private void dataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(bool?))
        {
             DataGridCheckBoxColumn  checkBoxColumn=new DataGridCheckBoxColumn();
            checkBoxColumn.Header = e.Column.Header;
            checkBoxColumn.Binding = new Binding(e.PropertyName);
            checkBoxColumn.IsThreeState = true;

            // Replace the auto-generated column with the checkBoxColumn.
            e.Column = checkBoxColumn;
           }
    }

这篇关于当 AutoGenerateColumns for nullable bool 时,WPF DataGrid 强制绑定 DataGridCheckBoxColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆