2016-06-24 210 views
0

我需要使我的DataGrid列可編輯,但無法弄清楚如何做到這一點。 當我嘗試編輯列時,我發現異常「EditItem不允許用於此視圖」。使WPF DataGrid列可編輯

我的XAML:

<DataGrid IsReadOnly="False" AutoGenerateColumns="False" Margin="6,6,5,18" Name="dataGrid1" ItemsSource="{Binding MyDictionary}" CellEditEnding="dataGrid1_editCells"> 
     <DataGrid.Columns> 
      <DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Key}" /> 
      <DataGridTextColumn IsReadOnly="False" Header="Value" Binding="{Binding Value}" /> 
     </DataGrid.Columns> 
    </DataGrid> 

而且的.cs:

public partial class MyView : Window 
{ 
    private Dictionary<string, string> myDictionary = new Dictionary<string, string>(); 

    public Dictionary<string, string> Dictionary { get { return myDictionary ; } set { myDictionary = value; } } 

    public MyView() 
    { 
     // Here is some code that fills dictionary 

     InitializeComponent(); 
     this.DataContext = this; 
    } 
} 

問題是什麼?我怎樣才能讓我的第二列可編輯?

+0

爲什麼不使用observablecollection? – riteshmeher

回答

1

如果綁定到字典,它將枚舉內容作爲KeyValuePair實例,這是一個結構。您不能編輯保留相同實例的結構的成員(並且在這種情況下屬性是隻能獲取的)。

改爲綁定到類實例的列表。

+0

實際上,您可以更改結構的成員,但不建議使用 – wiero

+0

@wiero:當您訪問一個結構時,您會得到一個結構的副本,因此如果您編輯該結構,則不會更改您可能「意指」的實例編輯。您需要將該實例重新分配給哪個實例,哪些綁定不會執行。 –

+0

謝謝,現在我明白你的意思了 – wiero

0

DataGrid與集合一起使用,Dictioanry是KeyValuePair的集合。如果你看看這個結構,你會看到它不可變。