用于网格控制WPF的动态列

时间:2015-06-15 14:15:24

标签: c# wpf mvvm

我在wpf视图中有一个网格控件,我从文件中读取更多字段,我想在视图模型中为这些字段生成列(我使用MVVM)。所以我有一个类似的功能:

GridColumn column;
            try
            {
                column = new GridColumn
                {
                    Name = fieldName,
                    Header = headerName,
                    AllowSorting = DefaultBoolean.True,
                    FieldName = fieldName,
                    ReadOnly = isReadOnly,
                    AllowEditing = isReadOnly ? DefaultBoolean.False : DefaultBoolean.True,
                    AllowMoving = DefaultBoolean.True,
                    AllowResizing = DefaultBoolean.True,
                    Width = width,
                    EditSettings = new TextEditSettings { HorizontalContentAlignment = EditSettingsHorizontalAlignment.Center },
                    AllowDrop = true,
                    CellStyle = isDiffColumn ? GetDiffColumnStyle(fieldName) : null
                };
            }

但现在我想在我的网格中添加3个带按钮或图像的新列。所以我想我需要设置细胞模板。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

If you want to add a Column with either a Button or Image, you'll need to define a DataGridTemplateColumn.

For example:

var templateColumn = new DataGridTemplateColumn();
var template = new DataTemplate();
var button = new Button();
template.VisualTree = button; 
templateColumn.CellTemplate = template;