[C#][WPF]使DataGrid可以用滑鼠左鍵點一下立刻可以編輯

  • 829
  • 0
  • 2016-04-02

DataGrid預設是點一下為選取,點兩下為編輯,為了讓使用者在DataGrid上編輯時,有較好的使用體驗,必須改成點一下立刻可以編輯。

實現上述功能需要到DataGrid的DataGridCell的PreviewMouseLeftButtonDown事件內做處理,首先,在DataGrid的Xaml標籤內定義Style,
Xaml如下:

<DataGrid x:Name="dataGrid1" Margin="10,43,10.2,10.4" ItemsSource="{Binding}">
   <DataGrid.Resources>
      <Style TargetType="DataGridCell">
         <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
      </Style>
   </DataGrid.Resources>
   
</DataGrid>

接著,在Code-Behind撰寫事件處理函示如下:


//事件處理函式
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
  PreviewMouseLeftButtonDownHandle((DataGridCell)sender, this.datagrid1);
}


private void PreviewMouseLeftButtonDownHandle(DataGridCell cell, DataGrid datagrid)
{
			
  if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
  {
	if (!cell.IsFocused)
	{
	  cell.Focus();
	}

	if (datagrid.SelectionUnit != DataGridSelectionUnit.FullRow)
	{
	  if (!cell.IsSelected)
	  {
	    cell.IsSelected = true;
	  }
	}
	else
	{
	  DataGridRow row = FindVisualParent<DataGridRow>(cell);
	  if (row != null && !row.IsSelected)
	  {
		row.IsSelected = true;
	  }
	}
  }
}

public 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;
}