控件TextBox,相关事件KeyDown、TextChanged,事件处理函数如下:
- private void textBox1_KeyDown(object sender, KeyEventArgs e)
- {
- TextBox txt = sender as TextBox;
- //屏蔽非法按键
- if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() == "Tab" || e.Key == Key.Subtract)
- {
- if ((txt.Text.Contains(".") && e.Key == Key.Decimal) || (txt.Text.Contains("-") && e.Key == Key.Subtract))
- {
- e.Handled = true;
- return;
- }
- e.Handled = false;
- }
- else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod || e.Key == Key.OemMinus) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
- {
- if ((txt.Text.Contains(".") && e.Key == Key.OemPeriod) || (txt.Text.Contains("-") && e.Key == Key.OemMinus))
- {
- e.Handled = true;
- return;
- }
- e.Handled = false;
- }
- else
- {
- e.Handled = true;
- }
- }
- private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
- {
- if (textBox1.Text.Length == 1 && textBox1.Text == "-")
- e.Handled = true;
- else
- {
- //屏蔽中文输入和非法字符粘贴输入
- TextBox textBox = sender as TextBox;
- TextChange[] change = new TextChange[e.Changes.Count];
- e.Changes.CopyTo(change, 0);
- int offset = change[0].Offset;
- if (change[0].AddedLength > 0)
- {
- double num = 0;
- if (!Double.TryParse(textBox.Text, out num))
- {
- textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
- textBox.Select(offset, 0);
- }
- }
- }
- }
WPF TextBox 获得焦点后,文本框中的文字全选中
textbox.GotFocus 事件处理 Textbox.SelectAll() 是不行的, 这样处理会发生的情况是:
1) textbox1 当前没有焦点, 内容为 someText.
2) 鼠标点击 textbox1, 若单击点位于 someText 之内, 则 someText 被瞬间全选后所有的选择都被取消, 若单击点位于 someText 之外, 则不会发生任何事情, 没有任何选中的内容.
如下是解决办法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LIKE_textBox.PreviewMouseDown += new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown);//注意,这个事件的注册必须在LIKE_textBox获得焦点之前 LIKE_textBox.GotFocus += new RoutedEventHandler(LIKE_textBox_GotFocus); LIKE_textBox.LostFocus += new RoutedEventHandler(LIKE_textBox_LostFocus); } void LIKE_textBox_LostFocus(object sender, RoutedEventArgs e) { LIKE_textBox.PreviewMouseDown += new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown); } void LIKE_textBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) { LIKE_textBox.Focus(); e.Handled = true; } void LIKE_textBox_GotFocus(object sender, RoutedEventArgs e) { LIKE_textBox.SelectAll(); LIKE_textBox.PreviewMouseDown -= new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown); } } |