将Row添加到Datagrid时,C#WPF会抛出System.InvalidOperationException

时间:2016-03-19 13:25:00

标签: c# wpf xaml datagrid

我有一个WPF DataGrid,想要用代码添加数据。

XAML:

<DataGrid CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False" Name="WareneingangEinbuchenGrid" VerticalAlignment="Top" >
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="Name" Header="Name" Binding="{Binding Name}" />
                    <DataGridTextColumn x:Name="StueckzahlName" Header="Stückzahl" Binding="{Binding Stueckzahl}" />
                    <DataGridTextColumn x:Name="Preis" Header="Preis" Binding="{Binding Preis}" />
                    <DataGridTextColumn x:Name="Barcode" Header="Barcode" Binding="{Binding Barcode}" />
                </DataGrid.Columns>
            </DataGrid>

数据类:

    public class WareneingangGridData
{
    public string Name { get; set; }

    public int Stueckzahl { get; set; }

    public double Preis { get; set; }

    public string Barcode { get; set; }
}

XAML.cs:

WareneingangEinbuchenGrid.Items.Add(new WareneingangGridData { Name = "Testname", Stueckzahl = 2, Preis = 12.3 , Barcode = "TestBarcode" });

执行XAML.CS时,应用程序抛出System.InvalidOperationException错误。

1 个答案:

答案 0 :(得分:0)

找到了解决方案,我编辑了XAML.cs:

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
        {
            WareneingangEinbuchenGrid.Items.Add(new WareneingangGridData { Name = "Testname", Stueckzahl = 2, Preis = 12.3, Barcode = "TestBarcode" });
        }));