views:

232

answers:

2

Hi

In a datagrid I have two DataGridComboBoxColumns. The items of one of these columns should depend on what is selected in the other column. The underlying collection used to model this is a dictionary<string,List<string>>. How should i go about implementing this? I can't seem to hook up to any relevant events on the columns, and I cant find any databinding scenarios that support this..

A: 

I had the same scenario a while back and fixed it like this:

  public class DataItem : INotifyPropertyChanged {
  ...

  public List<SomeObject> DisplayableComboBoxItems { 
 get; set;
}

private static Dictionary<int, List<SomeObject>> myDict; 

public Dictionary<int, List<SomeObject>> MyDict {
 get {
  if (myDict == null) {
   myDict = GetYourDataFromSomewhere();
  }
  return myDict;
 }
}

public int TypeId {
 get { return typeId; }
 set {
  if (value == typeId) return;
  typeId = value;
  RaisePropertyChanged("TypeId");
 }
}

public int TypeSetId {
 get { return typeSetId; }
 set {
  if (typeSetId == value) return;   
  typeSetId = value;
  RaisePropertyChanged("TypeSetId");
  DisplayableComboBoxItems = MyDict[typeSetId];
  RaisePropertyChanged("DisplayableComboBoxItems");
  TypeId = 0;                
 }
}
...
}

DataItem is the object that gets bound to a DataRow. This is just a small mock-up of the code. Basically, whenever the TypeSet changes, I needed a new list of Types to be displayed. I used just a static list, in this example i used a dictionary.
With this setup you can bind you combobox ItemsSource to the 'DisplayableComboBoxItems', and your SelectedValue to "TypeId". You're gonna need other properties to display the correct text instead of the TypeId.
The downside of this is that when you have 1000+ items, you'll have that same list for all items. This wasn't however the case with me (DataGrid showed max 50 items).

I hope this is clear enough and that it helps you in the right direction!

cheers!
Roel

Roel
thank for the answer Roel, very helpful, but I ended up pursuing a different solution.
fsl
A: 

Instead of using a DataGridComboBoxColumn for the second column, I went with a DataGridTemplateColumn with an embedded Combobox. For the itemsource i defined a converter: string -> List<string>. The converter translates the value of the selecteditem of the other DataGridComboBox (which is bound to Navn) into List<string>, this is just a dictionary lookup.

Like so:

<my:DataGridTemplateColumn>
                <my:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox  SelectedItem="{Binding Værdi}" 
                                    ItemsSource="{Binding Navn,  Converter={StaticResource dimensionToValues}}"
                                   > 
                        </ComboBox>
                    </DataTemplate>
                </my:DataGridTemplateColumn.CellTemplate>
            </my:DataGridTemplateColumn>
fsl