C#-DataGridColumn只能输入数字

2023-11-07 746 2

写一个比较通用的方法,扩展一个新的格式列DataGridNumericColumn继承DataGridTextColumn,在DataGridNumericColumn类中限制输入,参考代码:

public class DataGridNumericColumn : DataGridTextColumn
{
    protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
    {
        var edit = editingElement as TextBox;
        edit.PreviewTextInput += Edit_PreviewTextInput;
        DataObject.AddPastingHandler(edit, OnPaste);
        //限制输入法切换,可避免中文输入添加到列中
        InputMethod.SetIsInputMethodEnabled(edit,false);
        return base.PrepareCellForEdit(editingElement, editingEventArgs);
    }

    private void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        var data = e.SourceDataObject.GetData(DataFormats.Text);
        if (!IsDataValid(data)) e.CancelCommand();
    }

    private void Edit_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !IsDataValid(e.Text);
    }

    bool IsDataValid(object data)
    {
        try
        {
            Convert.ToInt32(data);
            return true;
        }
        catch
        {
            return false;
        }
    }
}

参考:

WPF的DataGrid中只能输入数字的列 - k10j - 博客园 (cnblogs.com)

相关文章

C#-获取常用的路径
C#-DataGridComboBoxColumn数据绑定
C#-Devexpress GridControl 标题内容居中
C#-Group By 的使用
【转】C#-Blazor组件间通信
【转】C#-Consul配置中心

评论(2)

发布评论