How add row to DataGrid?

半腔热情 提交于 2020-01-07 07:56:09

问题


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.


回答1:


Here is explanation. ItemsSource collection must implement some interfaces for it to work.




回答2:


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.



来源:https://stackoverflow.com/questions/28363243/how-add-row-to-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!