动态添加wpf datagrid中的复选框列

时间:2014-08-25 07:22:07

标签: c# wpf mvvm datagrid

我正在使用WPF数据网格来显示使用MVVM的细节。此数据网格的列根据用户在运行时动态定义。它工作正常。但是,我需要在此数据网格中包含“复选框”列以及现有字段。我使用了以下代码。

...

foreach (var column in collection)
{
  GridColumnAdd(gridView, column);
}

...

private static void GridColumnAdd(DataGrid gridView, DataGridColumns columnName)
    {

        if (columnName.DisplayColumnName == "Print")
        {
            var column = new DataGridCheckBoxColumn();

            column.Header = columnName.DisplayColumnName;
            column.Binding = new Binding();

            var binding = (column.Binding as Binding);
            binding.Mode = BindingMode.TwoWay;

            if (binding != null)
            {
                IValueConverter converter = binding.Converter = new ColumnValueConverter(); // Will work here
                binding.ConverterParameter = columnName.BindingPropertyName;
            }

            gridView.Columns.Add(column);

        }
        else
        {
            var column = new DataGridTextColumn();

            column.IsReadOnly = true;
            column.Header = columnName.DisplayColumnName;
            column.Binding = new Binding();
            var binding = (column.Binding as Binding);
            if (binding != null)
            {
                IValueConverter converter = binding.Converter = new ColumnValueConverter(); // Will work here
                binding.ConverterParameter = columnName.BindingPropertyName;
            }
            gridView.Columns.Add(column);

        }
    }

在运行时我遇到异常“双向绑定需要Path或XPath”。

您能否帮我动态地在现有的datagrid列中包含复选框列?

1 个答案:

答案 0 :(得分:1)

Binding()构造函数中的路径定义为Binding("IsChecked")

请参阅this链接,您将获得一些帮助。如果你仍然不知道如何做到这一点。在此答案中添加评论。