如何以编程方式将数据添加到 WPF 数据网格 [英] How to add Data to a WPF datagrid programatically

查看:32
本文介绍了如何以编程方式将数据添加到 WPF 数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有绑定的 WPF 中以编程方式将数据项添加到 DataGrid?DataGrid 有 4 列.

How can I add data Items to a DataGrid programmatically in WPF which do not have bindings? The DataGrid has 4 columns.

推荐答案

不是很清楚,你喜欢做什么.我想,你已经定义了一些你想要放置 DataGrid 的地方.出于说明目的,我创建了一个新的 WPF 项目并使用了 chridram 提供的代码,他发布了第一个答案.

It is not very clear, what You like to do. I guess, You have defined some place where You want to put the DataGrid. For illustration purposes, I created a new WPF project and use the code provided by chridram, who posted the first answer.

在下面的 MainWindow.xaml 中,我将 Grid 命名为 MainGrid 以在后面的代码中访问它:

In the following MainWindow.xaml I name the Grid MainGrid to access it in the code behind:

<Window x:Class="WpfExperiments.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="MainGrid"/>
</Window>

DataItem 类不是 WPF 类,而是自己创建的自定义类:

The DataItem class is not a WPF class, but a custom class created by Yourself:

public class DataItem
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
    public string Column3 { get; set; }
    public string Column4 { get; set; }
}

要让 DataGrid 以编程方式显示存储在 DataItem 对象中的数据,您可以执行以下操作:

To let the DataGrid display data stored in DataItem objects programmatically, You may do the following:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // Your programmatically created DataGrid is attached to MainGrid here
        var dg = new DataGrid();
        this.MainGrid.Children.Add(dg);

        // create four columns here with same names as the DataItem's properties
        for (int i = 1; i <= 4; ++i)
        {
            var column = new DataGridTextColumn();
            column.Header = "Column" + i;
            column.Binding = new Binding("Column" + i);
            dg.Columns.Add(column);
        }

        // create and add two lines of fake data to be displayed, here
        dg.Items.Add(new DataItem { Column1 = "a.1", Column2 = "a.2", Column3 = "a.3", Column4 = "a.4" });
        dg.Items.Add(new DataItem { Column1 = "b.1", Column2 = "b.2", Column3 = "b.3", Column4 = "b.4" });
    }
}

我希望这会有所帮助.

您好约尔格

这篇关于如何以编程方式将数据添加到 WPF 数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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