I, like so many, ne开发者_开发技巧ed to create a Numeric textbox control in WPF. I've made good progress so far, but I'm not sure what the right approach is for the next step.
As part of the control's spec, it must always display a number. If the user highlights all the text and taps backspace or delete, I need to ensure that the value is set to zero, not "blank." How should I do this in the WPF control model?
What I have so far (abbreviated):
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
}
}
On the one hand, this is simple and seems to work ok. I'm not sure that it's correct though because we're always (if ever-so-briefly) setting the text to be blank before we reset it to be zero. There's no PreviewTextChanged event that lets me manipulate the value before it's changed, though, so this is my best guess.
Is it correct?
Why not simply make use of your OnPreviewTextInput
handler to check if the incoming value is an int or not, attempt to convert it...
Convert.ToInt32(e.Text);
If the conversion fails, it is not an int and therefore mark it as handled so the text won't change.
While this may slightly violate your need, ie...deleting all text would not revert to 0, it would however remain an int. I personally think that from a UI perspective this is more logical, in that why does clearing all input move the value to 0? That in and of itself defines the TextBox
as accepting non int values since the UI changes under those conditions.
精彩评论