wpf datagrid:在wpf中创建一个DatagridNumericColumn [英] wpf datagrid : create a DatagridNumericColumn in wpf
问题描述
我有一个要求,当用户输入数字以外的其他内容来处理文本框时,我想创建一个仅接受数字值(整数)的datagridcolumn。
我尝试了很多网页,对此感到厌倦,非常感谢任何人的帮助。
I have a requirement that I want to make a datagridcolumn which only accepts numeric values(integer) ,when the user enter something other than numbers handle the textbox . I tried a lot of webpages ,Iam tired of these ,I greately appreciate anybody have the helping mind.
推荐答案
根据@nit的建议,您可以创建从 DataGridTextColumn
派生的自己的类,如下所示:
Based on @nit suggestion, you can create your own class derived from DataGridTextColumn
like this:
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)
{
try
{
Convert.ToInt32(e.Text);
}
catch
{
// Show some kind of error message if you want
// Set handled to true
e.Handled = true;
}
}
}
在PrepareCellForEdit 方法,您注册了 OnPreviewTextInput
方法编辑 TextBox
PreviewTextInput 事件,您可以在其中验证数值。
In the PrepareCellForEdit method you register the OnPreviewTextInput
method to the editing TextBox
PreviewTextInput event, where you validate for numeric values.
在xaml中,您只需使用它即可:
In xaml, you simply use it:
<DataGrid ItemsSource="{Binding SomeCollection}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding NonNumericProperty}"/>
<local:DataGridNumericColumn Binding="{Binding NumericProperty}"/>
</DataGrid.Columns>
</DataGrid>
希望这会有所帮助
这篇关于wpf datagrid:在wpf中创建一个DatagridNumericColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!