using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Input; using System.Windows; namespace DyeingComputer.UserClass { /// /// DataGrid中只能输入数字的列 /// /// local:DataGridNumericColumn Binding = "{Binding NumericProperty}" /// public class NumericTextColumn : 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; } } } }