我在 XAML 中有一个 DataGrid,其中每一列都是一个文本列。我为每一列定义了一个列模板。我希望能够在单元格上单击一次并处于编辑模式,而不必双击它。我遵循了这个:http ://wpf.codeplex.com/wikipage?title=Single-Click%20Editing并且我没有成功。现在,下面显示的示例代码只会让单元格在单击中获得焦点,它实际上不会让我进入编辑模式。任何帮助将不胜感激!
这是数据网格:
<DataGrid
DockPanel.Dock="Bottom"
x:Name="grdData"
FontFamily="Verdana"
Height="200"
AutoGenerateColumns="False"
RowHeight="22"
CanUserAddRows="True"
CanUserDeleteRows="True"
CanUserReorderColumns="False"
CanUserResizeColumns="True"
CanUserResizeRows="True"
CanUserSortColumns="True"
ItemsSource="{Binding GridData}"
SelectionUnit="CellOrRowHeader"
SelectionMode="Extended">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter
Event="PreviewMouseLeftButtonDown"
Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
</Style>
</DataGrid.Resources>
这是我定义的示例列模板:
<DataGridTemplateColumn Width="60">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<TextBlock
Style="{StaticResource tbkStyleGridHeader}"
TextWrapping="Wrap"
Text="GelPak Location"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Style="{StaticResource tbkStyleGridCell}"
TextWrapping="Wrap"
Text="{Binding GelPakLocation}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox
Text="{Binding GelPakLocation, Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
这是代码隐藏:
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = (DataGridCell) sender;
if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
{
if (!cell.IsFocused)
{
cell.Focus();
}
DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
if (dataGrid != null)
{
if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
{
if (!cell.IsSelected)
{
cell.IsSelected = true;
cell.IsEditing = true;
}
}
else
{
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null && !row.IsSelected)
{
row.IsSelected = true;
}
}
}
}
}
static T FindVisualParent<T>(UIElement element) where T : UIElement
{
UIElement parent = element;
while (parent != null)
{
T correctlyTyped = parent as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}
parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
return null;
}