내용 보기

작성자

관리자 (IP : 172.17.0.1)

날짜

2020-07-10 02:07

제목

[WPF] DataGrid Tips & Tricks: Single-Click Editing


xaml Resources에 다음과 같이 Style을 추가 한다.

XAML

<Window.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"></EventSetter>
        </Style>
</Window.Resources>
cs

cs에서 다음처럼 이벤트 처리를 한다.

CS

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<DataGrid>(cell);
                if (dataGrid != null)
                {
                    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;
                        }
                    }
                }
            }
}
 
private 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;
}
cs


출처1

출처2