在vs中添加一个新的类,在工程中右键,出现如下视图
命名为CustomizedTextBox.cs
添加如下代码- public class CustomizedTextBox:TextBox
- {
- private readonly List<Key> _defualtKeys = new List<Key>{
- Key.NumPad0, Key.NumPad1, Key.NumPad2, // 默认只允许输入数字键和删除键
- Key.NumPad3, Key.NumPad4, Key.NumPad5, // 注:在其它键盘上数字键可能为Key.D0等
- Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9, Key.Back};
- private List<Key> _listKeys; // 允许输入的键集合
- public List<Key> ListKeys // 定义属性
- {
- get { return _listKeys; }
- set { _listKeys = value; }
- }
- public CustomizedTextBox()
- {
- _listKeys = new List<Key>();
- _listKeys = _defualtKeys;
- this.InputScope = new InputScope();
- this.InputScope.Names.Add(new InputScopeName{NameValue = InputScopeNameValue.TelephoneNumber});
- }
- public CustomizedTextBox(List<Key> listKeys)
- {
- _listKeys = new List<Key>();
- _listKeys = listKeys;
- this.InputScope = new InputScope();
- this.InputScope.Names.Add(new InputScopeName { NameValue = InputScopeNameValue.TelephoneNumber });
- }
- protected override void OnKeyDown(KeyEventArgs e)
- {
- if (!_listKeys.Contains(e.Key))
- {
- e.Handled = true; // 拦截事件,再允许这个行为被其它地方处理ª
- // 即只让_listKeys集合里的键能够输入
- }
- base.OnKeyDown(e); // 调用基类默认的操作
- }
- }
复制代码 定义好后我们如何使用呢?
1) 如上图添加命名空间xmlns: my="clr-namespace:UIControlSets"
2) 在xmal文件中添加如下代码- <my:CustomizedTextBox Height="100" Margin="31,358,25,149" />
复制代码 如果用c#方式:- List<Key> list = new List<Key> { Key.D0, Key.D1, Key.D2 }; // 允许输入的字符
- CustomizedTextBox ctb = new CustomizedTextBox(list);
- this.LayoutRoot.Children.Add(ctb);
复制代码 可自定义允许输入的字符
|