Pergunta

In my C# WPF application (.NET 4.0) I have a DataGrid dynamically filled from code including a DataGridComboBoxColumn:

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

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

    return cboColumn;
}

Using the BeginningEdit event different checks are performed.

If the checks return okay, I want to expand the combobox directly, otherwise edit mode is cancelled:

void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    ...
    if(notOK)
        e.Cancel;
    else {
        DataGridComboBoxColumn dgCboCol = (DataGridComboBoxColumn)e.Column;
        // expand dgCboCol
    }
    ...
}

Questions: How to expand the combobox programmatically? Is BeginningEdit event the right place to do that?


Answer:

void dataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
    if (e.EditingElement.GetType().Equals(typeof(ComboBox)))
    {
        ComboBox box = (ComboBox)e.EditingElement;
        box.IsDropDownOpen = true;
    }
}
Foi útil?

Solução 2

From DataGridBeginningEditEventArgs, you could access the generated element for the cell about to be edited like this:

var contentComboBox = e.Column.GetCellContent(e.Row) as ComboBox;

However, I'm not sure that this will get the actual ComboBox you need. DataGrids can generate two different elements for each cell, depending on whether they are in edit mode (read-only and read-write elements). Since BeginningEdit happens just before entering edit mode, this will get the read-only element.

The better event to handle this in would probably be PreparingCellForEdit, which will fire after BeginEdit is actually called on the data item (in other words, if BeginningEdit was not canceled). In that event, you can access the element directly through the EditingElement property.

Outras dicas

Take a look at this

Try setting edit mode on the grid to a single click and then use the CellClick event to obtain the comboBox and expand it.

dataGrid.BeginEdit(true); 
ComboBox comboBox = (ComboBox)dataGrid.EditingControl; 
comboBox.IsDropDownOpen = true;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top