【问题标题】:Make WPF DataGrid column editable使 WPF DataGrid 列可编辑
【发布时间】:2016-06-24 07:15:26
【问题描述】:

我需要使我的 DataGrid 列可编辑,但不知道如何做到这一点。 当我尝试编辑列时,我发现异常“此视图不允许 EditItem”。

我的 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;
    }
}

有什么问题?如何使我的第二列可编辑?

【问题讨论】:

  • 为什么不使用 observablecollection?

标签: c# wpf xaml datagrid


【解决方案1】:

如果您绑定到字典,它会将内容枚举为KeyValuePair 实例,这是一个结构。您不能编辑保持相同实例的结构的成员(在这种情况下,属性是 get-only)。

改为绑定到类实例列表。

【讨论】:

  • 其实可以改变结构体的成员,但不推荐
  • @wiero:当您访问一个结构时,您会得到它的副本,因此如果您编辑该结构,您将不会更改您可能“打算”编辑的实例。您需要将该实例重新分配到它的来源,而绑定不会这样做。
  • 谢谢。就是这样!
【解决方案2】:

DataGrid 与集合一起使用,而 Dictioanry 是 KeyValuePair 的集合。如果您查看此结构,您会发现它不是可变的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2011-08-23
    • 2014-10-10
    • 1970-01-01
    • 2011-08-23
    • 2011-09-14
    相关资源
    最近更新 更多