我的wpf应用程序中有DataGrid。这是一些事件。我需要单击编辑datagrid单元格。当我双击单元格时,它正在改变。我抓了一些东西。但是,它对我不起作用。行和列不一致。动态地,我将为Datagrid创建列。
这是我的代码..
的Xaml:
<DataGrid Name="dgTest" AutoGenerateColumns="True" CanUserResizeColumns="False" CanUserAddRows="False"
ItemsSource="{Binding NotifyOnSourceUpdated=True}"
HorizontalAlignment="Left"
SelectionMode="Single"
SelectionUnit="Cell"
IsSynchronizedWithCurrentItem="True"
CellStyle="{StaticResource DataGridBorder}"
CurrentCellChanged="dgTest_CurrentCellChanged"
CellEditEnding="dgTest_CellEditEnding"
GotFocus="dgTest_GotFocus" LostFocus="dgTest_LostFocus"
GotKeyboardFocus="TextBoxGotKeyboardFocus" LostKeyboardFocus="TextBoxLostKeyboardFocus"
AutoGeneratingColumn="dgTest_AutoGeneratingColumn"/>
我曾经去过&#34; GotFocus&#34;事件。但它不适合我。任何帮助都会得到真正的重视。
CS:
private void dgTest_GotFocus(object sender, RoutedEventArgs e)
{
// Lookup for the source to be DataGridCell
if (e.OriginalSource.GetType() == typeof(DataGridCell))
{
// Starts the Edit on the row;
DataGrid grd = (DataGrid)sender;
grd.BeginEdit(e);
}
}
答案 0 :(得分:1)
试试这个:
在DataGrid上连接PreviewMouseLeftButtonDown事件:
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter
Event="PreviewMouseLeftButtonDown"
Handeler="DataGridCell_PreviewMouseLeftButtonDown"/>
</Style>
</DataGrid.Resources>
然后在后面的代码中:
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = (DataGridCell) sender;
if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
{
if (!cell.IsFocused)
{
cell.Focus();
}
if (grdData.SelectionUnit != DataGridSelectionUnit.FullRow)
{
if (!cell.IsSelected)
{
cell.IsSelected = 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;
}