wpf datagrid : create a DatagridNumericColumn in wpf

前端 未结 6 935
迷失自我
迷失自我 2021-02-14 11:33

I have a requirement that I want to make a datagridcolumn which only accepts numeric values(integer) ,when the user enter something other than numbers handle the textbox . I tri

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 11:40

    I got here looking for a solution to the same problem: constraining the input into cells on a DataGrid to be numeric. But the accepted answer did not work for me. The following did:

    1. For the DataGrid add an event handler for PreparingForCellEdit.
    2. In that event handler, cast the EditingElement to a TextBox and add an event handler for PreviewTextInput to the TextBox.
    3. In the PreviewTextInput event handler set e.Handled to true, if the input should not be allowed.

    The above steps work if the user clicks the cell to edit. However, if the cell is not in edit mode, the PreparingForCellEdit event will not be called. To perform validation in that case:

    1. Add an event handler to the DataGrid for PreviewTextInput.
    2. In that event handler, safely cast e.OriginalSource to a DataGridCell (exiting, if it is not a DataGridCell), check the DataGridCell's IsEditing property, and if the cell is not editing set e.Handled to true.

    The effect of the above is that the user will have to click into the cell in order to edit its contents and, as such, the PreparingForCellEdit / PreviewTextInput combination above will be invoked for all changes to the cell's contents.

提交回复
热议问题