wpf datagrid:在wpf中创建DatagridNumericColumn

作者:编程家 分类: swift 时间:2025-06-16

在WPF中,DataGrid是一个非常常用的控件,用于在界面上展示和编辑数据。然而,当我们需要在DataGrid中显示数值类型的数据时,自带的DataGridTextColumn并不能满足我们的需求,因为它只能接受文本类型的输入。为了解决这个问题,我们可以自定义一个DatagridNumericColumn,使其只接受数字类型的输入。

首先,我们需要创建一个继承自DataGridTextColumn的类,并命名为DatagridNumericColumn。接下来,我们需要重写一些方法,以便在需要的时候验证用户输入的数据类型。

csharp

public class DatagridNumericColumn : DataGridTextColumn

{

protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)

{

var textBox = editingElement as TextBox;

if (textBox != null)

{

textBox.PreviewTextInput += NumericOnlyTextInput;

DataObject.AddPastingHandler(textBox, NumericOnlyPasteInput);

}

return base.PrepareCellForEdit(editingElement, editingEventArgs);

}

private void NumericOnlyTextInput(object sender, TextCompositionEventArgs e)

{

foreach (var c in e.Text)

{

if (!char.IsDigit(c))

{

e.Handled = true;

break;

}

}

}

private void NumericOnlyPasteInput(object sender, DataObjectPastingEventArgs e)

{

if (e.DataObject.GetDataPresent(typeof(string)))

{

var pastedText = (string)e.DataObject.GetData(typeof(string));

if (!string.IsNullOrEmpty(pastedText))

{

foreach (var c in pastedText)

{

if (!char.IsDigit(c))

{

e.CancelCommand();

break;

}

}

}

}

else

{

e.CancelCommand();

}

}

}

在上述代码中,我们重写了PrepareCellForEdit方法,在进入编辑模式时,给TextBox添加了PreviewTextInput和DataObject.AddPastingHandler事件。这两个事件分别用于在用户输入和粘贴时验证输入的数据类型。通过遍历输入的字符,我们可以判断是否为数字类型,如果不是,则将输入事件标记为已处理。这样,就实现了只接受数字类型输入的功能。

下面,我们来演示一下如何在XAML中使用自定义的DatagridNumericColumn。首先,我们需要在XAML文件中引入自定义的命名空间:

xaml

xmlns:local="clr-namespace:YourNamespace"

然后,我们可以像使用其他DataGrid列一样,将DatagridNumericColumn添加到DataGrid中:

xaml

在上述代码中,我们创建了一个DataGrid,并添加了一个DatagridNumericColumn。通过设置Header属性和Binding属性,我们可以为列指定标题和数据绑定。

案例代码:

为了更好地理解和使用DatagridNumericColumn,我们可以创建一个简单的案例来演示它的用法。

首先,我们创建一个名为Person的类,用于表示一个人的信息,其中包含一个数值类型的属性Age:

csharp

public class Person

{

public int Age { get; set; }

}

接下来,在MainWindow.xaml.cs文件中,我们创建一个ObservableCollection的属性People,用于存储人员信息。在MainWindow的构造函数中,我们初始化People并添加一些示例数据:

csharp

public partial class MainWindow : Window

{

public ObservableCollection People { get; set; }

public MainWindow()

{

InitializeComponent();

People = new ObservableCollection

{

new Person { Age = 20 },

new Person { Age = 30 },

new Person { Age = 40 }

};

DataContext = this;

}

}

最后,在MainWindow.xaml文件中,我们使用DataGrid和DatagridNumericColumn来展示People的数据:

xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:YourNamespace"

Title="MainWindow" Height="450" Width="800">

通过自定义DatagridNumericColumn,我们可以在WPF中创建一个只接受数字类型输入的DataGrid列。通过重写一些事件和方法,我们可以实现对用户输入的验证,从而确保只有数字类型的数据被输入。在实际的应用中,我们可以根据需要对DatagridNumericColumn进行扩展和定制,以满足各种复杂的数据输入需求。