2012-01-21 151 views
0

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

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

;

回答

0

嗯,你没有分配ItemsSource,你添加一个项目到Items集合,这是一个完全不同的事情。

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

+0

嗯,我有种重做项目。我会告诉你我在下面的代码中做了什么。谢谢。 – mdietz

+0

@MichaelDietz:请在上面而不是下面,评论不适合代码。 –

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> 

在你的类只绑定一个List(任何枚举)与DataGrid

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

这样,您可以编辑您的DataGrid中,每个项目将被添加到列表

+0

谢谢。我远离XAML只是为了看看能否用代码做所有事情。我不得不首先使用System.Collections.Generic指定一个指令来使用列表,然后必须在主类结构中将公共列表中的列表 1stData或myList定义为public。最后,它并没有刷新新的添加,所以我不得不在新项目添加后运行dataGrid1.Items.Refresh()。再次感谢! – mdietz

0

使您的ItemsSource作为ObservableCollection完美工作 ObservableCollection itmSrcLevels = new ObservableCollection(ItemsSrc1);