简体   繁体   English

如何将行添加到DataGrid?

[英]How add row to DataGrid?

I have small program for edit XML-files. 我有一个用于编辑XML文件的小程序。 I using XMLDataProvider: 我使用XMLDataProvider:

<Grid.DataContext>
    <XmlDataProvider x:Name="XMLData" Source="/database/stroyka1.bas" XPath="JobArray/job"/>
</Grid.DataContext>

and DataGrid: 和DataGrid:

<DataGrid 
    Name="JobsDataGrid" 
    ItemsSource="{Binding}"
    AutoGenerateColumns="false" Height="Auto" Width="Auto"
    IsReadOnly="False" CanUserAddRows="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding XPath=id, Mode=TwoWay}" />
        <DataGridTextColumn Header="Название" Binding="{Binding XPath=name, Mode=TwoWay}" />
        <DataGridTextColumn Header="Цена за единицу" Binding="{Binding XPath=price, Mode=TwoWay}"/>
        <DataGridTextColumn Header="Единица измерения" Binding="{Binding XPath=measure, Mode=TwoWay}"/>
    </DataGrid.Columns>
</DataGrid>

How to enable a blank row below the table? 如何启用表格下方的空白行? CanUserAddRow=true and IsReadOnly=false not work. CanUserAddRow=trueIsReadOnly=false无效。 I tried add row with blank parameters to DataGrid, but have error: 我尝试将带有空白参数的行添加到DataGrid,但是出现错误:

Operation is not allowed when using ItemsSource. 使用ItemsSource时不允许进行操作。 Instead, access and modify elements using ItemsControl.ItemsSource. 而是使用ItemsControl.ItemsSource访问和修改元素。

Here is explanation. 是解释。 ItemsSource collection must implement some interfaces for it to work. ItemsSource集合必须实现一些接口才能起作用。

Thanks a lot, but i find method, but i crutch for this question. 非常感谢,但是我找到了方法,但是我想问这个问题。 I use this code: 我使用以下代码:

private void AddNewRowMenuItem_OnClick(object sender, RoutedEventArgs e)
    {
        job pipainput = new job(JobsDataGrid.Items.Count+1,"",0,"");
        XmlSerializer xmls = new XmlSerializer(typeof(job));
        var sb = new StringBuilder(512);

        using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))
            {
                xmls.Serialize(sw, pipainput);
            }

        XmlDocument xmlk = new XmlDocument();
        xmlk.LoadXml(sb.ToString());

        XmlNode pipa = XMLData.Document.ImportNode(xmlk.ChildNodes[1], true);
        XMLData.Document.DocumentElement.AppendChild(pipa);
    }    

when job - my class. 上班时间-我的班级。 Works perfectly. 完美运作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM