且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何添加DataGrid行?

更新时间:2023-12-03 17:01:52

非常感谢,但是找到方法,但我这个问题的拐杖。我使用这个代码:

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

使用(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);
}

工作 - 我的课程。完美无瑕。


I have small program for edit XML-files. I using XMLDataProvider:

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

and 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. I tried add row with blank parameters to DataGrid, but have error:

Operation is not allowed when using ItemsSource. Instead, access and modify elements using ItemsControl.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.