我在 WPF 中有一個簡單的庫存管理器,它使用一個數據網格連接到一個表,前幾天使用 SQL 工作,但更改了一行代碼,現在它壞了。自從我把它弄壞后我就睡著了,不知道怎么修好它。問題似乎與下面 MainWindow 類中的 dataGrid1.Items.Add(testtables) 有關。我在 trycatch 中運行它時出現異常消息,指出在使用 ItemsSource 時該操作無效,應該使用 ItemsControl.ItemsSource 來訪問和修改元素。這是主窗體的代碼namespace WpfApp2{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { DataClasses1DataContext dc = new DataClasses1DataContext(Properties.Settings.Default.TestingConnectionString); public MainWindow() { InitializeComponent(); if (dc.DatabaseExists()) { dataGrid1.ItemsSource = dc.TestTables; } } private void newButton_Click(object sender, RoutedEventArgs e) { Window1 window1 = new Window1(); window1.Show(); } public void NewLine (int ID, string nm, decimal pc) { TestTable testtable = new TestTable { ID = ID, Name = nm, Price = pc }; dataGrid1.Items.Add(testtable); } private void saveButton_Click_1(object sender, RoutedEventArgs e) { dc.SubmitChanges(); } }}MainWindow 的 XAML 代碼<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid>
1 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
在您的代碼的這一部分:
public MainWindow()
{
InitializeComponent();
if (dc.DatabaseExists())
{
dataGrid1.ItemsSource = dc.TestTables;
}
}
您通過將數據表分配給 datagrid.ItemsSource 屬性來顯示數據。如果這樣做,您需要通過修改 DataTable 而不是 DataGrid 來添加項目。
dataGrid1.Items.Add(testtable);
因此,嘗試將 testtable 項目添加到現有集合 dc.TestTables 而不是上面的內容
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消