Single click edit in WPF DataGrid

前端 未结 11 1555
野的像风
野的像风 2020-11-27 10:47

I want the user to be able to put the cell into editing mode and highlight the row the cell is contained in with a single click. By default, this is double click.

H

11条回答
  •  离开以前
    2020-11-27 11:13

    From: http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing

    XAML:

    
    
    

    CODE-BEHIND:

    //
    // SINGLE CLICK EDITING
    //
    private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
        {
            if (!cell.IsFocused)
            {
                cell.Focus();
            }
            DataGrid dataGrid = FindVisualParent(cell);
            if (dataGrid != null)
            {
                if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                {
                    if (!cell.IsSelected)
                        cell.IsSelected = true;
                }
                else
                {
                    DataGridRow row = FindVisualParent(cell);
                    if (row != null && !row.IsSelected)
                    {
                        row.IsSelected = true;
                    }
                }
            }
        }
    }
    
    static T FindVisualParent(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;
    }
    

提交回复
热议问题