1

我使用以下代码订阅了SelectionChangedEventa ComboBoxin a :DataGrid

public static DataGridTemplateColumn CreateComboboxColumn(string colName, Binding textBinding, SelectionChangedEventHandler selChangedHandler = null)
{
    var cboColumn = new DataGridTemplateColumn {Header = colName};
...
    if (selChangedHandler != null)
        cboFactory.AddHandler(Selector.SelectionChangedEvent, selChangedHandler);
...
    return cboColumn;
}

我实际注册的处理程序包含:

private void ComboBoxSelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
    Console.WriteLine(@"selectHandler");
    var cboBox = sender as ComboBox;
    if (cboBox == null)
        return;

    if (cboBox.IsDropDownOpen) // a selection in combobox was made
    {
        CommitEdit();
    }
    else // trigger the combobox to show its list
        cboBox.IsDropDownOpen = true;
}

...并且位于我的自定义DataGrid类中。

如果我在 ComboBox 中选择一个项目,e.AddedItemscboBox.SelectedItem包含所选值,但CommitEdit().

DataGrid当用户在下拉列表中选择一个项目时,我想要强制提交直接更新ItemsSource。通常,如果控件失去焦点,则会引发此问题...

此线程中找到的解决方案中的链接不再可用,我不知道如何使用此代码。

4

1 回答 1

1

我为我的问题创建了一个棘手但有效的解决方案。这是上面修改后的处理程序:

private void ComboBoxSelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
    Console.WriteLine(@"selectHandler");
    var cboBox = sender as ComboBox;
    if (cboBox == null)
        return;

    if (cboBox.IsDropDownOpen) // a selection in combobox was made
    {
        cboBox.Text = cboBox.SelectedValue as string;
        cboBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
    }
    else // user wants to open the combobox
        cboBox.IsDropDownOpen = true;
}

因为我的 ComboBoxColumn 是自定义DataGridTemplateColumn的,所以当用户第一次选择单元格时,我强制它显示其列表。

要更改绑定的项目值,我用最近选择的项目手动覆盖显示的文本,并强制 UI 选择另一个项目(在本例中为右侧的控件)以对CellEditEnding事件进行隐式调用,这(在我的情况下)提交整行:

private bool _isManualEditCommit = false;
private void _CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    // commit a manual edit
    // this if-clause prevents double execution of the EditEnding event
    if (!_isManualEditCommit)
    {   
        Console.WriteLine(@"_CellEditEnding() manualeditcommit");
        _isManualEditCommit = true;
        CommitEdit(DataGridEditingUnit.Row, true);
        _isManualEditCommit = false;
        checkRow(e.Row);
    }
}

也许我可以用这个“肮脏”的解决方案帮助别人;-)

于 2013-10-28T10:45:53.723 回答