I have a Window
with a DataGrid
with Companies
in it. A user clicks 'Edit', a new Window
opens and the SelectedCompany
is passed to the ModifyWindow
. Now this all works as expected, and if the user clicks Save
on the ModifyWindow
the SelectedCompany
is updated on sql and the changed are reflected in the DataGrid
on the main Companies
Window.
However, if the user makes changes to the Company
in the ModifyWindow
and does not click save but instead closes the Window
using the cross (to me clearly saying that they want to throw away this edit) then the Company
is still updated on the DataGrid
. Here is some code:
From the CompaniesViewModel
:
private void ShowEditCompanyWindow()
{
var modifyCompanyViewModel = new ModifyCompanyViewModel(SelectedCompany);
modifyCompanyViewModel.ReturnModifiedCompany += LoadModifiedCompany;
Messenger.Default.Send(modifyCompanyViewModel);
}
private void LoadModifiedCompany(Company modifiedCompany)
{
var existingCompany = DataGridCompanies.FirstOrDefault(c => c.Id == modifiedCompany.Id);
var i = DataGridCompanies.IndexOf(existingCompany);
DataGridCompanies[i] = modifiedCompany;
var existingSearchCompany = AllSearchCompanies.FirstOrDefault(s => s.Id == modifiedCompany.Id);
var x = AllSearchCompanies.IndexOf(existingSearchCompany);
if (existingSearchCompany != null)
{
existingSearchCompany.Name = modifiedCompany.Name;
existingSearchCompany.Town = modifiedCompany.Town;
AllSearchCompanies[x] = existingSearchCompany;
}
SelectedCompany = modifiedCompany;
SearchCompanyView = CollectionViewSource.GetDefaultView(AllSearchCompanies) as CollectionView;
Application.Current.MainWindow.Activate();
}
From the ModifyCompanyViewModel
:
private async void ProcessCompany(Window window)
{
var waitView = new WaitView
{
Owner = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive)
};
waitView.Show();
if (await EditCompany())
{
ReturnModifiedCompany(SelectedCompany);
CloseWindow(window);
}
waitView.Close();
}
The DataGrid
on CompaniesView
:
<DataGrid Grid.Row="1" x:Name="CompaniesDataGrid" Margin="5"
ItemsSource="{Binding DataGridCompanies}"
SelectedItem="{Binding SelectedCompany}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Town" Width="*" Binding="{Binding Town}"/>
<DataGridTextColumn Header="Telephone" Width="*" Binding="{Binding Telephone}"/>
</DataGrid.Columns>
</DataGrid>
I'm new to MVVM
and I'm thinking now that I don't have to do the updating of the Company
in the DataGridCompanies
as MVVM
will handle this for me. My bigger issue though is how the SelectedCompany
still changes in the DataGrid
even though they have closed the modify window and do not want to commit. I have tried binding the Closing event on the modify window and storing an unmodified Company and return that, however the Company
in the DataGrid
still changed regardless.