0

In my C# WPF application I programmatically add a ComboBoxColumn to a DataGrid:

public static DataGridComboBoxColumn getCboCol(string colName, Binding textBinding)
{
    List<string> statusItemsList = new StatusStrList();

    DataGridComboBoxColumn cboColumn = new DataGridComboBoxColumn();
    cboColumn.Header = colName;
    cboColumn.SelectedItemBinding = textBinding;
    cboColumn.ItemsSource = statusItemsList;

    return cboColumn;
}

If an item in the containing DataGrid contains text, which my StatusStrList doesn't contain, it won't be displayed.

Example: If my StatusStrList contains A, B, C and a DataGrid's item has X, the X won't be displayed as text in the ComboBox.

How can I fix this?

Thanks in advance, Christian

Christian St.
  • 1,751
  • 2
  • 22
  • 41

1 Answers1

0

DataGridComboBoxColumn isn't dynamic enough to do something like this but you can use DataGridTemplateColumn. Code below should achieve the functionality you need. It works by using a CellTemplate containing a TextBlock which easily displays an item that wouldn't be in the ItemsSource of the ComboBox. Going into edit mode will bring up the ComboBox that contains all of the items of the list.

        DataGridTemplateColumn cboColumn = new DataGridTemplateColumn();
        cboColumn.Header = colName;

        //DataTemplate for CellTemplate
        DataTemplate cellTemplate = new DataTemplate();
        FrameworkElementFactory txtBlkFactory = new FrameworkElementFactory(typeof(TextBlock));
        txtBlkFactory.SetValue(TextBlock.TextProperty, textBinding);
        cellTemplate.VisualTree = txtBlkFactory;
        cboColumn.CellTemplate = cellTemplate;

        //DataTemplate for CellEditingTemplate
        DataTemplate editTemplate = new DataTemplate();
        FrameworkElementFactory cboFactory = new FrameworkElementFactory(typeof(ComboBox));
        cboFactory.SetValue(ComboBox.TextProperty, textBinding);
        cboFactory.SetValue(ComboBox.ItemsSourceProperty, statusItemsList);
        cboFactory.SetValue(ComboBox.IsEditableProperty, true);

        MouseEventHandler handler = new MouseEventHandler(delegate(object sender, MouseEventArgs args)
        {
            ComboBox cboBox = (ComboBox)sender;
            cboBox.IsDropDownOpen = true;
        });

        cboFactory.AddHandler(ComboBox.MouseEnterEvent, handler);

        editTemplate.VisualTree = cboFactory;
        cboColumn.CellEditingTemplate = editTemplate;
jamesSampica
  • 12,230
  • 3
  • 63
  • 85
  • Thanks, I'll try that out soon. Does your code fit to [this question](http://stackoverflow.com/questions/18252269/how-to-expand-the-combobox-in-a-wpf-datagridcomboboxcolumn)? – Christian St. Aug 22 '13 at 10:10
  • @Christian I updated it to fit the requirements of your other question. I'm not sure exactly _how_ you want it to trigger but I think it's pretty clear how to change it. You can also remove the code from your previous question, it's all handled here. – jamesSampica Aug 23 '13 at 02:53