How to expand the ComboBox in a (WPF) DataGridComboBoxColumn?

♀尐吖头ヾ 提交于 2019-12-23 19:44:45

问题


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;
    }
}

回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/18252269/how-to-expand-the-combobox-in-a-wpf-datagridcomboboxcolumn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!