Hello, I am writing an application on WPF. I try to add records to the DataGrid, but they duplicate the columns and the table itself is not updated after they are added, although dg.ItemsSource.Count changes.
in markup:
<DataGrid x:Name="dg" Margin="10,30,0,0" RenderTransformOrigin="2.583,2.231" HorizontalAlignment="Left" VerticalAlignment="Top"> <DataGrid.Columns> <DataGridTemplateColumn Header="Image"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="{Binding Image}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Binding="{Binding Text}" Header="Text" MaxWidth="100"/> <DataGridHyperlinkColumn Binding="{Binding Link}" Header="Link"/> </DataGrid.Columns> </DataGrid> DG element class:
class Post { public string Text { get; set; } public string Link { get; set; } public ImageSource Image { get; set; } } Use in code:
private void button_Click(object sender, RoutedEventArgs e) { if (dg.Items.Count == 0) { ImageSource img = new BitmapImage(new Uri("Images/web.ico", UriKind.Relative)); posts.Add(new Post { Image = img, Link = "http://vk.com/id02", Text = "Some adds1" }); dg.ItemsSource = posts; } else { AddPost(); } } private void AddPost() { MessageBox.Show(dg.Items.Count.ToString()); ImageSource img = new BitmapImage(new Uri("Images/web.ico", UriKind.Relative)); posts.Add(new Post { Image = img, Link = "http://vk.com/id02", Text = "Some adds1" }); posts.Add(new Post { Image = img, Link = "http://vk.com/id01", Text = "Some adds2" }); posts.Add(new Post { Image = img, Link = "http://vk.com/id03", Text = "Some adds3" }); }