通过XAML向DataGrid添加行 [英] Adding rows to DataGrid through XAML

查看:154
本文介绍了通过XAML向DataGrid添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过XAML向WPF DataGrid添加一行或多行,而不将其绑定到集合。我正在寻找的东西基本上是这样的:

Is it possible to add one or more rows to WPF DataGrid through XAML, without binding it to a collection. What I'm looking for would essentially be something like:

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
    ...
    </DataGrid.Columns>

    <DataGrid.Items>
        <DataGridRow>
        ...
        </DataGridRow>
    </DataGrid.Items>
</DataGrid>

我将在设计时使用它来查看我的DataGrid列如何看起来像没有实际运行代码。

I'm going to use it at design-time to see how my DataGrid columns would look like without actually running the code.

推荐答案

感觉幸运。发现自己这是最简单的方法。

Feeling lucky. Found it myself. Here's the simplest way.

创建一个具有相同公共属性的虚拟类(重要的是将成员定义为属性而不是字段)。例如:

Create a dummy class with the same public properties (important that you define members as properties and not fields). For example:

public class Dummy
{
    public string Subject { get; set; }
    public string Body { get; set; }
    public DateTime DueDateStart { get; set; }       
}

通过在顶部添加以下导入将项目命名空间导入XAML:

Import your project namespace into XAML by adding the following import at the top:

xmlns:local="clr-namespace:YourProjectNamespace"

现在,您可以在设计时将项目(行)添加到DataGrid中(请确保您的列具有正确的绑定):

Now you can add items (rows) to your DataGrid at design-time like (make sure your columns have proper bindings):

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Subject" Binding="{Binding Path=Subject}"/>
      <DataGridTextColumn Header="Body" Binding="{Binding Path=Body}"/>
      <DataGridTextColumn Header="Due Date" Binding="{Binding Path=DueDateStart}"/>
    </DataGrid.Columns>

    <local:Dummy Subject="Subject 1" Body="Body 1" ... />
    <local:Dummy Subject="Subject 2" Body="Body 2" ... />
</DataGrid>

希望这有帮助!

这篇关于通过XAML向DataGrid添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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