【问题标题】:wpf datagrid cell edit error : ( A TwoWay or OneWayToSource binding cannot work on the read-only property)wpf datagrid 单元格编辑错误:(TwoWay 或 OneWayToSource 绑定无法在只读属性上工作)
【发布时间】:2019-11-21 07:11:43
【问题描述】:

我有一个具有以下属性的 DataGrid:

<DataGrid x:Name="dg_words" ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>  
                    <DataGridTextColumn Header="Id" Binding="{Binding id}" />
                    <DataGridTextColumn Header="word" Binding="{Binding word}" IsReadOnly="False"/>                        
                </DataGrid.Columns>
</DataGrid>

此 DataGrid 有两列。第一个是只读列 (Id),第二个是可编辑列 (word)。

我用一个列表来填充这个 DataGrid。

List<Tuple<int, string>> l = new List<Tuple<int, string>>();
l.Add(new Tuple<int, string>(1, "word 1"));
l.Add(new Tuple<int, string>(2, "word 2"));
l.Add(new Tuple<int, string>(3, "word 3"));

var l1 = (from p in l
          select new { Id = p.Item1, word = p.Item2 }).ToList();

dg_quran_words.ItemsSource = l1;

当我尝试编辑列 word 中的单元格时,抛出异常:

附加信息:TwoWay 或 OneWayToSource 绑定无法对类型为...的只读属性“word”起作用。

【问题讨论】:

  • 错误文本为您提供了问题的确切原因。创建一个类来表示具有 getset 访问器而不是匿名访问器的列表项
  • 我更新了一条评论,问题不在 xaml 中

标签: c# wpf datagrid


【解决方案1】:

谢谢Pavel Anikhouski

问题已通过 Pavel 在我的问题中的评论得到解决。 首先,添加以下类:

public class c_row
{
    public int id { get; set; }
    public string word { get; set; }
}

最后: 替换我的代码的最后 4 行以填充 DataGrid。

var l1 = (from p in l
      select new c_row { Id = p.Item1, word = p.Item2 }).ToList();

dg_quran_words.ItemsSource = l1;

【讨论】:

    猜你喜欢
    • 2010-10-10
    • 2012-02-05
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多