在WPF中使DataGrid可编辑

时间:2012-01-21 05:26:13

标签: wpf datagrid

我试图让dataGrid1可编辑。我读到我可以为List创建一个类实例,然后将其分配给DataGrid.ItemSource。这可能只有2行代码,但仍然挂了如何使用下面的代码。有任何想法吗?谢谢!

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上发布。这是我改变了,它对我有用。

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

我还必须添加

  

使用System.Collections.Generic;

3 个答案:

答案 0 :(得分:1)

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

      <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>

在您的类中仅使用DataGrid

绑定List(任何可枚举的)
      public MyClass
      {
           InitializeComponent();
           List<MyData> lstData = new List<MyData>();
           dataGrid1.ItemsSource = lstData;
      }

使用它可以编辑DataGrid,每个项目都将添加到List

答案 1 :(得分:0)

好吧,你没有分配ItemsSource,你在Items集合中添加了一个项目,这是一件完全不同的事情。

(另外,如果没有这样的属性,为什么要绑定到name?)

答案 2 :(得分:0)

使您的ItemsSource成为ObservableCollection以完美地运作 ObservableCollection itmSrcLevels = new ObservableCollection(ItemsSrc1);

相关问题