wpf datagrid : create a DatagridNumericColumn in wpf

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

    Based on @nit suggestion, you can create your own class derived from DataGridTextColumn like this:

    public class DataGridNumericColumn : DataGridTextColumn
    {
        protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
        {
            TextBox edit = editingElement as TextBox;
            edit.PreviewTextInput += OnPreviewTextInput;
    
            return base.PrepareCellForEdit(editingElement, editingEventArgs);
        }
    
        void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            try
            {
                Convert.ToInt32(e.Text);
            }
            catch
            {
                // Show some kind of error message if you want
    
                // Set handled to true
                e.Handled = true;
            }
        }
    }
    

    In the PrepareCellForEdit method you register the OnPreviewTextInput method to the editing TextBox PreviewTextInput event, where you validate for numeric values.

    In xaml, you simply use it:

        
            
                
                
            
        
    

    Hope this helps

提交回复
热议问题