wpf datagrid : create a DatagridNumericColumn in wpf

前端 未结 6 920
迷失自我
迷失自我 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:42

    Use TryParse instead, this helps to restrict input values to integer numbers only.

        /// 
        /// This class help to create data grid cell which only support interger numbers.
        /// 
        public class DataGridNumericColumn : DataGridTextColumn
        {
            protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
            {
                TextBox edit = editingElement as TextBox;
    
                if (edit != null) edit.PreviewTextInput += OnPreviewTextInput;
    
                return base.PrepareCellForEdit(editingElement, editingEventArgs);
            }
    
            private void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
            {
                int value;
    
                if (!int.TryParse(e.Text, out value))
                    e.Handled = true;
            }
        }
    

提交回复
热议问题