I'm binding a List<Product>
to a DataGrid
and Binding it properties to DataGridTextColumns
and I implemented INotifyPropertyChanged
for my ListProduct
When I change any property of Product, it will update in my DataGrid, but when a add or delete any Product, it will not update in DataGrid
My DataGrid
<DataGrid x:Name="ProductList" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Code" Binding="{Binding Code}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Value" Binding="{Binding Value, StringFormat=R\{0:C\}}"/>
</DataGrid.Columns>
</DataGrid>
And my code behind
public partial class PageProduct : Page, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<Pastel> _ListProduct;
public ObservableCollection<Pastel> ListProduct
{
get { return _ListProduct; }
set
{
_ListProduct = value;
this.OnPropertyChanged("ListProduct");
}
}
public PagePastel()
{
InitializeComponent();
UpdateList();
ProductList.ItemsSource = ListProduct; // ProductList is my DataGrid
}
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
private void UpdateList()
{
// db is my EntityContext
ListProduct = new ObservableCollection<Product>(db.Products.ToList());
}
private void btDeletar_Click(object sender, RoutedEventArgs e)
{
if (ProductList.SelectedItem != null)
{
Product product = ProductList.SelectedItem as Product;
db.Product.Remove(product);
db.SaveChanges();
if (SystemMessage.ConfirmDeleteProduct() == MessageBoxResult.No)
return;
SystemMessage.ProductDeleteSuccess();
UpdateList();
}
else
SystemMessage.NoProductSelected();
}
Where is problem? What can I do for DataGrid update list when I add or delete any register?