Reputation: 118
One of the view contains a DataGrid. The DataGrid is a list of materials and each material contain a unit that you can select via a DataGridComboBoxColumn.
The DataGrid and the DataGridComboBoxColumn are bound to two different ObservableCollection
in my view model, one for materials and one for units. These collections are initialized from a database on startup.
The problem is that when I first load the page after it got initialized, the DataGridComboBoxColumn does not have a selected value.
It is happening because the unit object inside the material object that is shown is not the same object as the one in the units collection initialized from the database.
This is the view code :
<DataGrid ItemsSource="{Binding Materials}" AutoGenerateColumns="False" Margin="10,10,10,0" Style="{StaticResource AzureDataGrid}">
<DataGrid.Columns>
<DataGridTextColumn Header="Matériel" Binding="{Binding Name, ValidatesOnDataErrors=True}" Width="*"/>
<mah:DataGridNumericUpDownColumn Header="Prix"
Binding="{Binding Price}"
StringFormat="C"
Minimum="0"
Width="*"/>
<DataGridComboBoxColumn Header="Unité"
ItemsSource="{Binding Source={StaticResource Units}}"
SelectedItemBinding="{Binding Unit, ValidatesOnDataErrors=True}"
DisplayMemberPath="Name"
Width="*"/>
</DataGrid.Columns>
</DataGrid>
This is the ViewModel code :
public MaterialViewModel(ISessionService sessionService, IMaterialRepository materialRepository)
{
_materialRepository = materialRepository;
Materials = sessionService.Materials;
Materials.CollectionChanged += MaterialsCollectionChanged;
foreach (var item in Materials)
{
item.PropertyChanged += MaterialPropertyChanged;
}
Units = sessionService.Units;
}
public ObservableCollection<Material> Materials { get; set; }
public ObservableCollection<Unit> Units { get; set; }
Just to be sure, I tried to initialize the units collection with the unit object that is in the material object and it was working as intended.
Anyone got a solution for this?
Thank you.
Upvotes: 0
Views: 149
Reputation: 169160
You could add a UnitName
or UnitId
property to the Material
class and bind to this one using the SelectedValueBinding
property. Don't forget to also set the SelectedValuePath
property to "Name" or whatever the value property of the Unit
class is called:
<DataGridComboBoxColumn Header="Unité"
ItemsSource="{Binding Source={StaticResource Units}}"
SelectedValueBinding="{Binding UnitName, ValidatesOnDataErrors=True}"
SelectedValuePath="Name"
DisplayMemberPath="Name"
Width="*"/>
Upvotes: 1