Tuesday, November 1, 2011

WPF DataGrid Combo Box Databinding

I'm using WPF and MVVM.

I have my View and my ViewModel.

My ViewModel has models of its own.

These models are used to communicate and translate data from a database.

I want my models to be POCOs and not to have more information than each should, for instance, I don't want my POCO model to contain a list of another item just so it knows which one it needs to reference. (This will make sense soon)

I have a PlateConfiguration that references PlateLocations and PlateTypes. I do not want my PlateConfiguration to contain a list of all PateLocations and PlateTypes, just the referenced PlateLocation and PlateType.

To accomplist this through databinding, you need to reference an ancestor and the DataContext of that ancestor.

Here is how:

Value="{Binding Path=DataContext.PlateTypes, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"

I am referencing the list of PlateTypes on my ViewModel within an element that has a different context.

The context of my element is:

ItemsSource="{Binding Configurations}"

This changes my context within the element. So, if I try and reference PlateTypes through binding, the element cannot.

Also, I want the selected PlateType to be set on the actual Database Model and not on the ViewModel.

I want the Displayed Value to be the Abbreviation Value that is set by the user.

To display the text of the desired value:

DisplayMemberPath="PlateTypeAbbrev"

This references the Configurations DataContext and not the ViewModel.

The entire code is:



Also,

I've changed the way I bind to my data. It seems more intuitive, but a problem arose, when I tried to change the values. You need to add "Mode=TwoWay, UpdateSourceTrigger=PropertyChanged"
to your binding. If you notice, I have changed the type of column in the DataGrid.