有一些信息的录入,比如电话号码,邮编等等的这些信息都只是需要输入数字,而Windows Phone 7里面的控件并没有只让输入数字的一个控件,那么要实现这样的一个控件就只能够手工地去扩展TextBox控件了。

扩展一个控件的步骤:

1、定义一个类,这个类需要继承你要扩展的控件的类

public class NumericTextBox : TextBox

2、在页面上添加扩展的控件的类的空间引用

xmlns:my="clr-namespace:WPNumericTextBox.Controls" 

3、调用控件

 <my:NumericTextBox x:Name="NumTbx"/>

下面是数字输入文本框控件的例子:

Windows Phone 7 扩展TextBox控件为数字输入文本框

控件类

NumericTextBox.cs

using System;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPNumericTextBox.Controls
{
public class NumericTextBox : TextBox
{
//返回键和数字键
private readonly Key[] numeric = new Key[] {Key.Back, Key.NumPad0, Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4,
Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };

public NumericTextBox()
{
//将文本设置为 电话号码的文本输入模式
this.InputScope = new InputScope();
this.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.TelephoneNumber });
}

protected override void OnKeyDown(KeyEventArgs e)
{
//如果是数字键或者返回键则设置e.Handled = true; 表示事件已经处理
if(Array.IndexOf(numeric,e.Key) == -1)
{
e.Handled
= true;
}
base.OnKeyDown(e); // important, if not called the back button is not handled
}
}

}

相关文章:

  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2021-10-01
  • 2021-08-31
猜你喜欢
  • 2021-10-16
  • 2021-11-05
  • 2022-12-23
  • 2021-09-23
  • 2021-09-14
  • 2021-11-15
相关资源
相似解决方案