I'm new in WPF. Now, I'm writing a project of WPF with Entity Framework. I can add and delete items correctly on my wpf; however, after I add or delete items, my datagrid still didn't refresh. Even I use the ssEntities.SaveChanges(); ssEntities.Refresh(RefreshMode.StoreWins, ssEntities.User);
How can I refresh my datagrid automatically with refresh function or another function ?
XAML
<Window.Resources>
<CollectionViewSource x:Key="UserViewSource"
d:DesignSource="{d:DesignInstance my:User, CreateList=True}" />
</Window.Resources>
<DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="537"
HorizontalAlignment="Left" ItemsSource="{Binding}" Margin="12,12,0,0"
Name="UserDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected"
VerticalAlignment="Top" Width="300"
SelectedCellsChanged="UserDataGrid_SelectedCellsChanged">
<DataGrid.Columns>
<DataGridTextColumn x:Name="IDColumn" Binding="{Binding Path=ID}" Header="ID"
Width="80" IsReadOnly="True" />
<DataGridTextColumn x:Name="NameColumn" Binding="{Binding Path=Name}"
Header="Name" Width="80" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
cs
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
if (ActionHandler == "Add")
{
User user = new User();
user.ID = ID;
user.Name = Name;
ssEntities.User.AddObject(user);
}
ssEntities.SaveChanges();
ssEntities.Refresh(RefreshMode.StoreWins, ssEntities.User);
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
DataContextis being set. 2 - I don't think it's a good idea to mash altogether UI and DB access like that, you'd better create an intermediate object layer to hold the data as intended to be shown in the UI. You will needObservableCollections for that. Please, don't put DB access code in a Button click event handler. - Federico BerasateguiObservableCollections instead. Also, I don't see where theDataContextis being set, therefore I couldn't tellWhattheDataContextactually is. - Federico Berasategui