在 WPF 中使 DataGrid 可编辑 [英] Making a DataGrid Editable in WPF

查看:158
本文介绍了在 WPF 中使 DataGrid 可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使 dataGrid1 可编辑.我读到我可以为 List 创建一个类实例,然后将它分配给 DataGrid.ItemSource.这可能只有 2 行代码,但仍然不知道如何使用以下代码来实现.有任何想法吗?谢谢!

I was trying to make dataGrid1 editable. I read that I can create a class instance to a List then assign it to DataGrid.ItemSource. This might only be 2 lines of code but still hung up on how to do it with the below code. Any ideas? Thanks!

public class MyData
{
    public string street { set; get; }
    public string town { set; get; }
}

DataGridTextColumn col1 = new DataGridTextColumn();
col1.Binding = new Binding("name");
dataGrid1.Columns.Add(col1);
dataGrid1.Items.Add((new MyData() { street = "5th ave", town = "neverland"}));

好的,感谢您的帮助.仍在努力习惯在 stackoverflow 上发帖.这是我改变的,它对我有用.

OK thanks for any help. Still trying to get used to posting on stackoverflow. Here is what I changed and it worked out for me.

List<MyData> MyListBox1 =new List<MyData>();
MyListBox1.Add(new MyData() { street = "5th ave", town = "neverland"}));
List<MyData> MyListBox1 =new List<MyData>();

我还必须添加

使用 System.Collections.Generic;

using System.Collections.Generic;

推荐答案

这是您想要的吗?在您的 XAML 代码中

Is this what you want? In your XAML code

      <DataGrid AutoGenerateColumns="False" Name="dataGrid1">
         <DataGrid.Columns>
            <DataGridTextColumn Header="Street" Binding="{Binding street}"/>
            <DataGridTextColumn Header="Town" Binding="{Binding town}"/>  
            <!-- by defect is editable -->

            <DataGridTextColumn Header="Town" Binding="{Binding town}" IsReadOnly="True"/>  
            <!-- Not editable -->

            ... more properties
         </DataGrid.Columns>
      </DataGrid>

在您的课程中,仅将 List(Any enumerable) 与 DataGrid 绑定

In your class only binding a List(Any enumerable) with the DataGrid

      public MyClass
      {
           InitializeComponent();
           List<MyData> lstData = new List<MyData>();
           dataGrid1.ItemsSource = lstData;
      }

这样你就可以编辑你的 DataGrid,每一项都将被添加到列表中

With that you can edit your DataGrid, every item will be added to the List

这篇关于在 WPF 中使 DataGrid 可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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