【发布时间】:2015-07-05 19:06:31
【问题描述】:
我的目标是实现一个带有组合框列的数据网格,用户可以通过单击鼠标进行选择。 我用谷歌搜索了这个问题,发现了很多解决方案(here 或here),它们都可以正常工作,UNTIL 用户在第一列中展开组合框,然后在第 2 列中选择组合框。问题在于首先单击第一个组合框只是失去焦点,只有在第二次单击后才会展开其他组合框。但是,它需要单击完成。
基本上,XAML 看起来像:
<DataGrid Name="grid" SelectionMode="Extended" HeadersVisibility="Column" SelectionUnit="Cell" >
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Name" Width="*" SelectedItemBinding="{Binding Path=Entity}" DisplayMemberPath="EntityName" >
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=Entities}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=Entities, Mode=TwoWay}"/>
<Setter Property="Uid" Value="cbEntMapping"/>
<EventSetter Event="SelectionChanged" Handler="CbFirmChanged" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
</Style>
</DataGridComboBoxColumn.CellStyle>
</DataGridComboBoxColumn>
<DataGridComboBoxColumn Header="Give Up"
Width="*"
SelectedItemBinding="{Binding Path=GiveUp}"
DisplayMemberPath="EntityName">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=GiveUp}"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=GiveUp, Mode=TwoWay}"/>
<EventSetter Event="SelectionChanged" Handler="CbFirmChanged" />
<Setter Property="Uid" Value="cbEntMapping"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
<DataGridComboBoxColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
</Style>
</DataGridComboBoxColumn.CellStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
这是当前单击编辑模式的实现:
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var cell = sender as DataGridCell;
GridColumnFastEdit(cell, e);
}
private void GridColumnFastEdit(DataGridCell cell, RoutedEventArgs e)
{
if (cell == null || cell.IsEditing || cell.IsReadOnly)
return;
var dataGrid = grid;
if (dataGrid == null)
return;
if (!cell.IsFocused)
{
cell.Focus();
}
var cb = cell.Content as ComboBox;
if (cb == null) return;
grid.BeginEdit(e);
cell.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
cb.IsDropDownOpen = true;
}
【问题讨论】:
-
尝试使用带有编辑模板的模板列作为组合框并在点击时设置为编辑模式?
-
感谢您的回复,我尝试了您的建议,但如果当前组合框被展开,我仍然需要第二次点击。
-
为此----这应该可以工作.... private void UIElement_OnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { combo.IsDropDownOpen = !combo.IsDropDownOpen; }
-
添加了格式化的答案..
标签: c# .net wpf datagrid combobox