WPF向XML绑定DataGrid添加行

时间:2013-10-22 18:23:05

标签: c# xml wpf vb.net datagrid

当我调试时,我无法向DataGrid添加行。

设置:我有一个XML文件(C:\ test.xml),我将其用作我的DataGrid的XmlDataProvider

XAML:

<Window x:Class="iDraft.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="185" Width="176">

<Grid>
    <Grid.DataContext>
        <XmlDataProvider x:Name="myData" XPath="Table/ENTRY" />
    </Grid.DataContext>

    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="True">
    <DataGrid.Columns>

            <DataGridTextColumn Header="Text" Binding="{Binding XPath=text, Mode=TwoWay}"/>

            <DataGridTemplateColumn Header="Combobox">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Text="{Binding XPath=combo, Mode=TwoWay}">
                            <ComboBoxItem>0</ComboBoxItem>
                            <ComboBoxItem>1</ComboBoxItem>
                            <ComboBoxItem>2</ComboBoxItem>
                            <ComboBoxItem>3</ComboBoxItem>
                            <ComboBoxItem>4</ComboBoxItem>
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>                
        </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace iDraft
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            myData.Source = new Uri(@"C:\test.xml");
        }
    }
}

XML(test.xml):

<?xml version="1.0" encoding="utf-8" ?>
<Table>
  <ENTRY>
    <text>1</text>
    <combo>1</combo>
  </ENTRY>
  <ENTRY>
    <text>2</text>
    <combo>1</combo>
  </ENTRY>
</Table>

我挖掘了一些旧的vb.net代码,发现了以下内容:

Imports System.Xml
Imports System.Data

Class MainWindow
 Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    Dim xmlFile As XmlReader
    Dim ds As New DataSet

    xmlFile = XmlReader.Create("C:\test.xml", New XmlReaderSettings())

    ds.ReadXml(xmlFile)

    xmlFile.Close()

    myData.Source = ds.Tables(0)

  End Sub
End Class

2 个答案:

答案 0 :(得分:1)

因为您的myData.Source是一个URI,所以它始终是只读的。您将需要将XML中的数据放入另一个介质(类/数据表)并处理添加/更新并将数据保存回XML格式。

答案 1 :(得分:0)

解决: 我摆脱了XmlDataProvider并在XAML中将XPath更改为Path。除此之外,我的后端代码保持不变(vb.net而不是C#代码)。

唯一需要注意的是绑定路径必须引用XML节点名称。