views:

21

answers:

1

VS 2010, WPF project.

I have a datagrid with text in all cells (data are from an array of custom objects). However I am unable to copy (ctrl+c) content of any cell. So I would like to use textboxes to display content of each cell. The real problem is I cannot do this in XAML but I have to do it dynamically in the code, because entire grid is build manually in code, so XAML only knows there is a grid.

I add the columns this way -- all I found related to column is that I can specify header template. How to build a cell template for it and set the widget to textbox?

            int i = 0;

            foreach (var db_col in query.FieldNames)
            {
                var col = new DataGridTextColumn();
                col.IsReadOnly = false;
                col.Header = db_col;
                col.Binding = new Binding(String.Format("Visual[{0}]", i));
                grid.Columns.Add(col);

                ++i;
            }

Thank you in advance.

Solved

Thanks to Marko, I finally came up with such solution.

        foreach (var db_col in query.FieldNames)
        {
                var template = new DataTemplate();
                var elemFactory = new FrameworkElementFactory(typeof(TextBox));
                elemFactory.SetBinding(TextBox.TextProperty, new Binding(String.Format("Visual[{0}]", i)));
                template.VisualTree = elemFactory;

                var col = new DataGridTemplateColumn();
                col.CellTemplate = template;
                col.IsReadOnly = true;
                col.Header = db_col;
                grid.Columns.Add(col);

                ++i;
        }
+1  A: 

First of all, the DataGridTextColumn uses a TextBlock to display data, when the cell is not in editing mode. Which is probably why you can't copy anything from it. Once you enter editing mode, the TextBlock is replaced with a TextBox and then you should be able to copy/paste as you normaly would.

Considering that the code you posted does not provide the functionality you want, I can only assume that you want to always show a TextBox. Inorder to do this, you need to use a DataGridTemplateColumn. So in your code behind you would create a new DataGridTemplateColumn, set it's CellTemplate to a new DataTemplate which inturn contains a TextBox. You should find some samples for creating a DataTemplate with a TextBox here: Can i create DataTemplate in code-behind?

Also note that if you do create a DataGridTemplateColumn you need to reimplement (if necessary) some behaviour that is built in to the other datagrid columns. For instance if the DataGrid is set to IsReadOnly = true, then your DataGridTemplateColumn with your TextBox is still editable. So you'd have to bind the TextBox.IsReadOnly property to the DataGrid.IsReadOnly property.

Marko
Great! Thank you. Initially I had problem with setting template for a cell, because I forgot to change the type of the column.
macias