I use a DataGrid
to display a list of Animals in my WPF application:
The value for ComboBox
"Bucht" is loaded from another collection Pens in my ViewModel using the following XAML, which works fine:
<DataGrid ItemsSource="{Binding Path=Animals, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" AutoGenerateColumns="False" CanUserSortColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="EPC" Binding="{Binding Epc, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Visual ID" Binding="{Binding VisualId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Geschlecht" Binding="{Binding Gender, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTemplateColumn Header="Bucht">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.Pens, RelativeSource={RelativeSource AncestorType={x:Type view:AdministrationView}}}"
DisplayMemberPath="Name"
SelectedItem="{Binding Pen, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding Pen.PenId}"
SelectedValuePath="PenId">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DataContext.SaveCommand, RelativeSource={RelativeSource AncestorType={x:Type view:AdministrationView}}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Now the problem: If the View is closed, e.g. by clicking on another View, some of the properties of my ViewModel are set to null. If I reopen the View the Pens are set to null which looks like that:
The debugger confirms it:
I think this is related to the question WPF View sets ViewModel properties to null on closing. But I can't use the workaround provided in those answers (i.e. setting UpdateSourceTrigger=LostFocus
in my ComboBox
) because I save the entity directly after edit, so LostFocus update is to late.
Is there any clean way to avoid that behaviour?