DataGrid Event

C# 공부중·2024년 10월 14일

WPF

목록 보기
15/18

내가 보려고 DataGird 만들면서 공부한 내용 적어놓기

DataGrid GotFocus(2024.10.15)

DataGird에서 포커스를 잡으면 실행되는 event 입니다.

당시 사용처 : GridData 에 DataGridCheckBoxColumn 을 만들고 보니.
두번 클릭해야 값이 변하는 불편한 상황이 발생
GotFocus를 이용해서 Check의 bool 값을 변경해주었다. 아래의 코드가 예시입니다.

주 의 사 항 : GotFocus는 새로운 Focus를 잡지않으면 event를 발생시키지않기때문에
Focus를 다른곳을 옮겨주면 같은 셀을 여러번 클릭해도 발동하고자 하는 함수를 계속 발동시킬수있습니다.

private void Grid_GotFocus(object sender, RoutedEventArgs e)
        {
            // OriginalSource 는 포커스를 준 ui요소를 가르키는 속성
            DataGridCell cell = e.OriginalSource as DataGridCell;
            
            if (cell != null && cell.Column is DataGridCheckBoxColumn)
            {
                xDataGridDailyDate.BeginEdit();

                CheckBox checkBox = cell.Content as CheckBox;
                if (checkBox != null)
                {
                    var rowIndex = xDataGridDailyDate.Items.IndexOf(cell.DataContext);
                    bool newIsCheckedValue = !checkBox.IsChecked ?? false;
                    checkBox.IsChecked = !checkBox.IsChecked;
                    m_FractionDailyModule.UpdateFractionDailyCompletion(rowIndex, newIsCheckedValue);
                    // focus를 옮겨줘서 다시 선택할때 되게 진행
                    xTextBoxTotalDose.Focus();
                }
                SumDailyDoseForChecked();
            }

        }

DataGrid CellEditEnding

DataGrid에서 editing 이 종료될시 실행되게 해주는 event

당시 사용처 : 날짜 변경일에 따라 변동되어야할 data가 있기에 날짜 입력후 함수실행을 위한 event 사용

 private void xDataGridDailyDate_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {    
            if (e.Row.Item is FractionDaily editedItem)
            {
                if (e.EditingElement is TextBox textBox)
                {
                    // 편집된 TextBox의 값 가져오기
                    var newValue = textBox.Text;
                    int rowIndex = e.Row.GetIndex();
                    var firstColumnContent = 
                    UpdateFractionDailyValue(editedItem, newValue, rowIndex);
                }
            }
        }

DataGrid IsEditing

DataGrid의 행 이나 열에 Editing 중인지 확인할수있는 속성입니다.

당시 사용처 : Grid 자체에 keyDown을 적용해서 DataGrid를 editing 할때는 그 keyDown이 적용되지않게 하기위해 작성

private bool IsDataGridEditing(DataGrid dataGrid)
        {
            foreach (var item in dataGrid.Items)
            {

                DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);
                if (row.IsEditing) // Row가 편집 중인 경우
                {
                    return false;
                }
                foreach (var column in dataGrid.Columns)
                {
                    DataGridCell cell = (DataGridCell)column.GetCellContent(row)?.Parent;
                    if (cell.IsEditing) // Cell이 편집 중인 경우
                    {
                        return false;
                    }
                }
            }
            return true;
        }

0개의 댓글