WPF:DataGrid中的复选框 [英] WPF: CheckBox in DataGrid

查看:1721
本文介绍了WPF:DataGrid中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态填充 DataGrid ,我也试图使一些列为 CheckBox 列。我这样做:

I'm dynamically filling a DataGrid and I'm also trying to make some columns as CheckBox columns. And I'm doing it this way :

DataTable dt = new DataTable();
dt.Columns.Add("First Column", typeof(String));
dt.Columns.Add("Second Column", typeof(Decimal));
dt.Columns.Add("Third Column", typeof(CheckBox));
    foreach (var i in Query)
        {
            List<Object> temp = new List<Object>();
                temp.Add(i.FirstValue);
                temp.Add(i.SecondValue);
                temp.Add(new CheckBox { IsChecked = false});                
            dt.Rows.Add(temp.ToArray());
        }
DataGrid1.ItemsSource = dt.DefaultView;

不幸的是我在DataGrid中看到的是一个 System.Windows.Controls。 CheckBox ,我也尝试了 DataGridCheckBoxColumn DataGridTemplate ,但只有对象的引用去那里。那么,什么是正确的方法把 CheckBox 放在 DataGrid 中。 (我知道如何在 XAML 中执行此操作,但我想知道如何从代码后面做)

Unfortunately what I see in my DataGrid is a System.Windows.Controls.CheckBox, I've also tried the DataGridCheckBoxColumn and also DataGridTemplate but only the object's reference goes there. So what is the right way to put the CheckBox in the DataGrid from the code. (I know how to do it in XAML but I wanna know how to do it from the code behind)

推荐答案

将第三列定义为 bool 类型。 WPF应自动将其作为复选框呈现。

Define the third column as type bool. WPF should automatically render it as a checkbox.

示例:

DataTable dt = new DataTable();
dt.Columns.Add("First Column", typeof(String));
dt.Columns.Add("Second Column", typeof(Decimal));
dt.Columns.Add("Third Column", typeof(bool));
foreach (var i in Query)
{
    List<Object> temp = new List<Object>();
    temp.Add(i.FirstValue);
    temp.Add(i.SecondValue);
    temp.Add(false);  // false => unchecked, true => checked.       
    dt.Rows.Add(temp.ToArray());
}

这篇关于WPF:DataGrid中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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