[英]How add row in DataGrid WPF
我不明白如何將內容從數據庫寫入 DataGrid。 這是代碼代碼 DataGrid
<DataGrid AutoGenerateColumns="False" x:Name="ColorsTable" HorizontalGridLinesBrush="DarkGray"
RowBackground="LightGray" AlternatingRowBackground="White" Grid.ColumnSpan="2" Margin="0,0,624.2,0">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path = Id}" Width="100" />
<DataGridTextColumn Header="Name" Binding="{Binding Path = Name}" Width="100" />
<DataGridTextColumn Header="Specification" Binding="{Binding Path = Specification}" Width="100" />
</DataGrid.Columns>
</DataGrid>
代碼添加
ObservableCollection<SomeAbstact> temp = new ObservableCollection<SomeAbstact>();
sqlCommand = new SqlCommand("SELECT * FROM [Colors]", SqlConnection);
reader = await sqlCommand.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
temp.Add(new Colors()
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
Specification = reader["Description"].ToString()
});
}
ColorsTable.ItemsSource = temp;
temp.Clear();
reader.Close();
實體添加
public class Colors: SomeAbstact
{
public int Id { get; set; }
public string Name { get; set; }
public string Specification { get; set; }
}
您可以像這樣將DataGrid
綁定到ObservableCollection
:
<DataGrid ItemsSource="{Binding temp}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}"/>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTextColumn Binding="{Binding Specification}"/>
</DataGrid.Columns>
</DataGrid>
這僅在正確設置DataContext
時才有效。 如果您想在 WPF 中使用綁定,您還應該查看如何實現INotifyPropertyChanged
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.