Как добавить строку в DataGrid WPF - PullRequest
0 голосов
/ 02 апреля 2020

Я не понимаю, как записать контент из базы данных в 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; }
}

1 Ответ

1 голос
/ 02 апреля 2020

Вы можете привязать DataGrid к ObservableCollection следующим образом:

<DataGrid ItemsSource="{Binding temp}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Id}"/>
            <DataGridTextColumn Binding="{Binding Name}"/>
            <DataGridTextColumn Binding="{Binding Specification}"/>
        </DataGrid.Columns>
    </DataGrid>

Это будет работать, только если DataContext установлен правильно. Также вам следует проверить, как реализовать INotifyPropertyChanged, если вы хотите использовать привязки в WPF.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...