Xaml的代码:
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="198,122,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" MaxLength="5" BorderBrush="#FF444444" Foreground="#FF3C4661" FontSize="13"
DataObject.Pasting="textBox_Pasting" InputMethod.IsInputMethodEnabled="False"
Text="0"
/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="0,122,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" MaxLength="5" BorderBrush="#FF444444" Foreground="#FF3C4661" FontSize="13"
DataObject.Pasting="textBox_Pasting" InputMethod.IsInputMethodEnabled="False"
Text="0"
/>
</Grid>
CS的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.AddHandler(TextBox.PreviewKeyDownEvent, new KeyEventHandler(textBox_PreviewKeyDown));
this.AddHandler(TextBox.PreviewTextInputEvent, new TextCompositionEventHandler(textBox_PreviewTextInput));
this.AddHandler(TextBox.TextChangedEvent, new TextChangedEventHandler(textBox_TextChanged));
this.AddHandler(TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(textBox_GotKeyboardFocus));
}
void textBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox == null)
{
return;
}
if (textBox.IsKeyboardFocused)
{
textBox.SelectionStart = textBox.Text.Length;
textBox.ScrollToEnd();
}
}
private void textBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!TextBoxHelper.IsNumberic(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
e.Handled = true;
}
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = false;
if (!TextBoxHelper.IsNumberic(e.Text))
{
e.Handled = true;
}
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox == null)
{
return;
}
textBox.SetTextValue();
}
}
public static class TextBoxHelper
{
public static void SetTextValue(this TextBox textBox)
{
int testInt = 0;
if (string.IsNullOrWhiteSpace(textBox.Text))
{
textBox.Text = testInt.ToString();
return;
}
if (textBox.Text.Length > 1)
{
textBox.Text = textBox.Text.TrimStart(new char[] { '0' });
}
textBox.Tag = textBox.Text;
textBox.SelectionStart = textBox.Text.Length;
textBox.ScrollToEnd();
}
public static bool IsNumberic(this string strValue)
{
if (string.IsNullOrEmpty(strValue))
return false;
foreach (char c in strValue)
{
if (!char.IsDigit(c))
{
return false;
}
}
return true;
}
}