C#-DataGridColumn只能输入数字

2023-11-08 11:04:06 浏览数 (2)

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

代码语言:javascript复制
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)

0 人点赞