我是 WPF 的新手,我想阻止用户输入字符,例如。字符“-”,所以我使用以下代码创建了自定义 DataGridTextColumn:
public class DataGridNumericColumn : DataGridTextColumn
{
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
var textBox = (TextBox) editingElement;
textBox.PreviewTextInput += OnPreviewTextInput;
return base.PrepareCellForEdit(editingElement, editingEventArgs);
}
private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = (TextBox)sender;
if (e.Text == "-")
return;
if (!this.IsNumeric(e.Text))
e.Handled = true;
}
}
和 XAML:
<ZF:ZFDataGrid
Grid.Row="4" Grid.Column="0"
HorizontalAlignment="Stretch" VerticalAlignment="Top"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
CanUserAddRows="True"
CanUserDeleteRows="False"
CanUserResizeRows="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
IsSynchronizedWithCurrentItem="True"
SelectionUnit="Cell"
SelectionMode="Single"
Margin="3,3,3,0"
AutoGenerateColumns="False"
AlternatingRowBackground="WhiteSmoke"
RowHeaderWidth="30"
FontSize="18"
ItemsSource="{Binding POSModel}">
<ZF:DataGridNumericColumn Header="Qty" Width="80" />
</ZF:ZFDataGrid>
自定义 DataGridNumericColumn 运行良好,除非我第一次按下该字符。如果我按 F2 编辑或双击列然后按 键,一切正常。
但是如果我在不先编辑单元格的情况下按下键,自定义 DataGridNumericColumn 将不起作用。
我在 PrepareCellForEdit 上放了断点,编码工作。但是当我按下键时,方法 OnPreviewTextInput 第二次起作用。不是第一个。
谁能给我另一个解决方案?
编辑:
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
var textBox = (TextBox) editingElement;
textBox.PreviewTextInput += OnPreviewTextInput;
textBox.TextChanged += OnTextChanged; //change here
return base.PrepareCellForEdit(editingElement, editingEventArgs);
}
此代码仅运行一次,其余的将由 OnPreviewTextInput 处理
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
if (textBox.Text.Contains("-"))
{
textBox.TextChanged -= OnTextChanged;
textBox.Text = "";
}
}