更新 DataGrid 的 ItemsSource on SelectionChanged 组合框事件
本文关键字:组合 事件 SelectionChanged on DataGrid ItemsSource 更新 | 更新日期: 2023-09-27 18:35:12
我用以下代码订阅了DataGrid
ComboBox
上的SelectionChangedEvent
:
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
类中。
如果我在组合框中选择一个项目,e.AddedItems
和cboBox.SelectedItem
包含所选值,但CommitEdit()
上没有任何更改。
我想要的是强制提交直接更新DataGrid
的 ItemsSource,当用户在下拉列表中选择一个项目时。通常,如果控件失去焦点,则会引发此问题...
在此线程中找到的解决方案中的链接不再可用,我不知道如何使用此代码。
我为我的问题创建了一个棘手但有效的解决方案。这是上面修改后的处理程序:
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);
}
}
也许我可以帮助某人解决这个"肮脏"的解决方案;-)