bovender framework
C# framework that implements MVVM and more
WpfHelpers.cs
1 /* WpfHelpers.cs
2  * part of Bovender framework
3  *
4  * Copyright 2014-2018 Daniel Kraus
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 using System;
19 using System.Collections.Generic;
20 using System.Linq;
21 using System.Text;
22 using System.Windows;
23 using System.Windows.Controls;
24 using System.Windows.Input;
25 using System.Windows.Media;
26 
27 namespace Bovender
28 {
29  public static class WpfHelpers
30  {
31  #region Public methods
32 
39  public static void RegisterTextBoxSelectAll()
40  {
41  // Select the text in a TextBox when it receives focus.
42  EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent,
43  new MouseButtonEventHandler(SelectivelyIgnoreMouseButton));
44  EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent,
45  new RoutedEventHandler(SelectAllText));
46  EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent,
47  new RoutedEventHandler(SelectAllText));
48  }
49 
50  #endregion
51 
52  #region Private methods
53 
54  static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
55  {
56  // Find the TextBox
57  DependencyObject parent = e.OriginalSource as UIElement;
58  while (parent != null && !(parent is TextBox))
59  parent = VisualTreeHelper.GetParent(parent);
60 
61  if (parent != null)
62  {
63  var textBox = (TextBox)parent;
64  if (!textBox.IsKeyboardFocusWithin)
65  {
66  // If the text box is not yet focused, give it the focus and
67  // stop further processing of this click event.
68  textBox.Focus();
69  e.Handled = true;
70  }
71  }
72  }
73 
74  static void SelectAllText(object sender, RoutedEventArgs e)
75  {
76  var textBox = e.OriginalSource as TextBox;
77  if (textBox != null)
78  textBox.SelectAll();
79  }
80 
81  #endregion
82  }
83 }
static void RegisterTextBoxSelectAll()
Make text boxes select all text on focus.
Definition: WpfHelpers.cs:39