我在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;
}
+1爲鏈接/教程 – Les