Wpf数值datagrid列用户控件编辑错误

时间:2016-10-15 17:37:59

标签: wpf user-controls

我想在datagrid用户控件中创建数字文本框。我创建使用下面的代码,它工作正常。 我的问题是,当我键入网格数字单元格允许第一个键字母,然后它限制字母表,只允许数字。

在WGrid XAML中

<DataGrid x:Class="WpfGrid.WGrid"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:WpfGrid"
         mc:Ignorable="d" 
         d:DesignHeight="300" Width="500" PreviewKeyDown="DataGrid_PreviewKeyDown" BeginningEdit="DataGrid_BeginningEdit" SelectionMode="Single" SelectionUnit="Cell" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeRows="False" CanUserSortColumns="False" CanUserResizeColumns="False" EnableRowVirtualization="False">

namespace WpfGrid
{
  public partial class WGrid : DataGrid
  {

    public WGrid()
    {
        InitializeComponent();
    }

  }
  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)
    {
        e.Handled = new Regex("[^0-9.]").IsMatch(e.Text);
    }
  }
}

创建此控件后,我在新的WPF应用程序中添加了它

XAML                                                                             

并以表格

public partial class MainWindow : Window
{
    ObservableCollection<Customer> collection = new    ObservableCollection<Customer>();
    public MainWindow()
    {
        InitializeComponent();
        collection.Add(new Customer());
        Dgv.ItemsSource = collection;
    }
    public class Customer
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public string Marks { get; set; }

    }

运行此DataGridNumericColumn后,它会限制第一个字符字母。 请告诉我如何纠正这个问题。用户控件名称为WGrid。

感谢。

Image of datagrid. You can see character a in weight column.It occurs only on begin edit

0 个答案:

没有答案