[英]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.