【问题标题】:How do I create a new row in WPF DataGrid when it is bound to an XmlDataProvider?绑定到 XmlDataProvider 时,如何在 WPF DataGrid 中创建新行?
【发布时间】:2009-01-26 15:13:31
【问题描述】:

我有一个项目,其 XmlDataProvider 绑定到 WPF DataGrid 控件。我在 DataGrid 上的绑定设置如下:

<dg:DataGrid ItemsSource="{Binding Source={StaticResource XmlData}, XPath=Root/People/Person}"
             AutoGenerateColumns="False">
    <dg:DataGrid.Columns>
        <dg:DataGridTextColumn Header="ID" Binding="{Binding XPath=ID}"/>
        <dg:DataGridTextColumn Header="Name" Binding="{Binding XPath=Name}"/>
    </dg:DataGrid.Columns>
</dg:DataGrid>

用户可以毫无问题地使用 DataGrid 编辑条目。我无法完成的是允许用户使用 DataGrid 添加新行(即新人员)。我怎么能允许呢?

【问题讨论】:

    标签: c# wpf wpftoolkit xmldataprovider


    【解决方案1】:

    确保您设置了:CanUserAddRows="True" 并且绑定类的默认构造函数可用。

    【讨论】:

    • 太棒了!我永远不会意识到默认构造函数是必要的
    • 您能否详细说明您对默认构造函数的含义?您如何使用 XmlDataSource 做到这一点?
    【解决方案2】:

    要向绑定到 XmlDataSource 的 WPF DataGrid 添加行,您需要直接修改支持数据存储。您可以使用 DataGrid 从用户那里收集新的行信息,然后在 RowEditEnding 事件中,您可以将行的信息添加到您的后备存储中,并防止 DataGrid 实际尝试使用其内在逻辑。由于 DataGrid 绑定到 XmlDataSource,它将显示您对后备存储所做的更改。

    大致思路如下:

    private void MyDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
      if (e.EditAction == DataGridEditAction.Cancel)
      {
        e.Cancel = false;
        return;
      }
    
      if (e.EditAction == DataGridEditAction.Commit)
      {
        DataGridRow dgr = e.Row;
        XmlElement xe = myXmlDataProvider.Document.CreateElement("NewRowElement");
        foreach(DataGridCell cell in dgr.Cells)
        {
          xe.SetAttribute(cell.Name, cell.Value);
        }
        dataProvider.Document.DocumentElement.AppendChild(xe);
        e.Cancel = true;
      }
    }
    

    【讨论】:

    • 我找不到来自dgr 或DataGridRow 的Cells 属性
    • 这是 4.0 之前的 WPF 信息——我认为行和单元格集合可能不再是公开的了?检查项目集合。我的回答的要点,即您需要修改后备数据存储,我认为仍然适用。
    【解决方案3】:

    您是否尝试过在 DataGrid 上设置 CanUserAddRows="True"?

    【讨论】:

    • 我今天遇到了同样的问题。我已明确设置 CanUserAddRows = true,但正如我从即时窗口中发现的那样,它立即变为 false。原因是绑定类没有默认构造函数。添加默认构造函数后,我在最后得到了新行。
    【解决方案4】:

    问题是用户无法添加行还是用户添加行时没有保存到支持 XML 存储?我可以轻松地将带有 CanUserAddRows="True" 的数据网格添加到 WPF 应用程序,将网格绑定到内存列表,然后让用户添加反映在该内存列表中的行。这让我觉得你的问题是保存到后备商店。

    当我绑定到文件系统上的 XML 时,我无法再将记录添加到数据网格。我认为您将需要一个较小的解决方法,因为您将文件读入内存中的集合,绑定到该集合,然后在用户添加行时相应地更新文件。

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      相关资源
      最近更新 更多