2012-01-21 48 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);