我和很多人一样,需要在 WPF 中创建一个数字文本框控件。到目前为止,我已经取得了很好的进展,但我不确定下一步的正确方法是什么。
作为控件规范的一部分,它必须始终显示一个数字。如果用户突出显示所有文本并点击退格或删除,我需要确保该值设置为零,而不是“空白”。我应该如何在 WPF 控制模型中做到这一点?
到目前为止我所拥有的(缩写):
public class PositiveIntegerTextBox : TextBox
{
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
// Ensure typed characters are numeric
}
protected override void OnPreviewDrop(DragEventArgs e)
{
// Ensure the dropped text is numeric.
}
protected override void OnTextChanged(TextChangedEventArgs e)
{
if (this.Text == string.Empty)
{
this.Text = "0";
// Setting the Text will fire OnTextChanged again--
// Set Handled so all the other handlers only get called once.
e.Handled = true;
}
base.OnTextChanged(e);
}
private void HandlePreviewExecutedHandler(object sender, ExecutedRoutedEventArgs e)
{
// If something's being pasted, make sure it's numeric
}
}
一方面,这很简单,似乎工作正常。我不确定它是否正确,因为我们总是(如果非常简单的话)将文本设置为空白,然后再将其重置为零。但是,没有 PreviewTextChanged 事件可以让我在值更改之前对其进行操作,所以这是我最好的猜测。
这是对的吗?