我有一个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错误。
答案 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" });
}));