在 wpf 中动态添加列到 DataGrid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15655271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:20:45  来源:igfitidea点击:

Dynamically add Columns to DataGrid in wpf

c#wpfwpfdatagriddrawingvisual

提问by Abhinav

I am currently working on a custom canvas and in that i have to add a table,So i thought dataGrid would be fine. SO i Want to create a "Table"from "Datagrid"by which user can add a table to the canvas at runtime.

我目前正在使用自定义画布,因此我必须添加一个表格,所以我认为 dataGrid 会很好。所以我想从“Datagrid”创建一个“表”,用户可以通过它在运行时向画布添加一个表。

Till now, I have tried to Populate DataGrid With a list and succeded.

到目前为止,我已经尝试使用列表填充 DataGrid 并成功。

How Can I add Columns to a Datagrid at runtime,such that the number of columns and header value Would be taken from the user at runtime using a textbox and based on the value of the textbox the datagrid should add columns and header value.

如何在运行时将列添加到数据网格,以便在运行时使用文本框从用户处获取列数和标题值,并根据文本框的值,数据网格应添加列和标题值。

Actually I want to develop a Table in which user passes the no of columns and the column header and the table should be generated.

实际上我想开发一个表,用户可以在其中传递列数和列标题,并且应该生成表。

Or

或者

"Can you suggest me with a way where i should look in order to to "Draw" a Table using DrawingVisual class"

“您能否建议我使用 DrawingVisual 类“绘制”表格时应该查看的方式”

It is a part of GraphicsTable Class

它是 GraphicsTable 类的一部分

//Custom Classes "DrawingCanvas & GraphicsTable" 
public void CreateDataGrid(GraphicsTable graphicsTable, DrawingCanvas drawingCanvas)
{
    dt = new DataGrid();
    dt.Name = "Data";
    dt.ItemsSource = person();
    dt.AllowDrop = true;
    dt.AutoGenerateColumns = true;
    dt.Height = graphicsTable.Rectangle.Height;
    dt.Width = graphicsTable.Rectangle.Width;
    drawingCanvas.Children.Add(dt);
    Canvas.SetTop(dt, graphicsTable.Rectangle.Top);
    Canvas.SetLeft(dt, graphicsTable.Rectangle.Left);
    dt.Width = dt.Width;
    dt.Height = dt.Height;
    dt.Focus();
}
//I have just tried to add dome dummy data to the datagrid.

public List<Person> person()
{
    List<Person> peep = new List<Person>();
    peep.Add(new Person() {});
    return peep;
}

public class Person
{
    private string name;
    private double salary;
    public string Names
    {
        get { return name; }
        set { name = value; }
    }
    public double Salary
    {
        get { return salary; }
        set { salary = value; }
    }
}

回答by Timothy Schoonover

You can dynamically build the columns of a DataGrid as follows.

您可以按如下方式动态构建 DataGrid 的列。

public void buildTable(string[] headers)
{
    myGrid.Columns.Clear();
    foreach (string header in headers)
    {
        DataGridTextColumn c = new DataGridTextColumn();
        c.Header = header;
        myGrid.Columns.Add(c);
    }
}

If you are setting ItemsSource, however, the number of rows and columns will automatically adjust to match the value of ItemsSource. For example, the following code produces a DataGrid with 3 rows and 3 columns.

但是,如果您正在设置 ItemsSource,则行数和列数将自动调整以匹配 ItemsSource 的值。例如,以下代码生成一个具有 3 行 3 列的 DataGrid。

dt = new DataTable();

for (int i = 0; i < 3; i++)
    dt.Columns.Add("col" + i.ToString());

for (int i = 0; i < 3; i++)
{
    DataRow r = items.NewRow();
    r[0] = "a" + i.ToString();
    r[1] = "b" + i.ToString();
    r[2] = "c" + i.ToString();
    dt.Rows.Add(r);
}

myGrid.ItemsSource = dt;
+------+------+------+  
| col0 | col1 | col2 |  
+------+------+------+  
|  a0  |  b0  |  c0  |  
+------+------+------+  
|  a1  |  b1  |  c1  |  
+------+------+------+  
|  a2  |  b2  |  c2  |   
+------+------+------+ 

Without knowing your exact requirements, I would not bother with manually drawing a table in code unless you have some special need custom graphics and even in that case I would look into using XAML to restyle the DataGrid or it's elements before attempting to render it myself. That's just my opinion though. Best of luck!

在不知道您的确切要求的情况下,除非您有一些特殊需要的自定义图形,否则我不会在代码中手动绘制表格,即使在这种情况下,我也会在尝试自己呈现之前使用 XAML 重新设计 DataGrid 或其元素的样式。不过这只是我的意见。祝你好运!

EDIT:

编辑:

If you want to generate the table columns based on user input, you would just need to put the column generation code in a event handler. In your example you could add an event handler for the Textbox TextChanged event as follows. This event handler will run every time the text changes in the Textbox. You may want to add validation to prevent users from keying in large numbers.

如果您想根据用户输入生成表列,您只需要将列生成代码放在事件处理程序中。在您的示例中,您可以为 Textbox TextChanged 事件添加一个事件处理程序,如下所示。每次文本框中的文本更改时,都会运行此事件处理程序。您可能希望添加验证以防止用户键入大量数字。

private void numColsTextbox_TextChanged(object sender, TextChangedEventArgs e)
{
    int numCols;
    if (Int32.TryParse(tb.Text, out numCols))
    {
        myGrid.Columns.Clear();
        for (int i = 1; i <= numCols; i++)
        {
            DataGridTextColumn c = new DataGridTextColumn();
            c.Header = "Column " + i.ToString();
            myGrid.Columns.Add(c);
        }
    }
}