在ComboBox的SelectionChanged事件上更新DataGrid的ItemsSource

时间:2013-10-14 14:24:55

标签: c# wpf .net-4.0 datagrid

我使用以下代码在SelectionChangedEvent的{​​{1}}订阅了ComboBox

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; } 课程中。

如果我在ComboBox中选择了一个项目,DataGride.AddedItems包含所选的值,但cboBox.SelectedItem上没有任何更改。

当用户选择下拉列表中的项目时,我想要强制提交直接更新CommitEdit()的ItemsSource。通常情况下,如果控件失去焦点,则会引发这种情况......

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

1 个答案:

答案 0 :(得分:0)

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

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

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