WPF自定义数字输入框控件
时间: 2023-10-04 08:12:18 浏览: 51
WPF自定义数字输入框控件可以通过继承自TextBox控件,重写一些基类的方法和属性,实现数字输入限制和格式化等功能,以下是一个简单的示例:
```csharp
public class NumberTextBox : TextBox
{
public NumberTextBox()
{
this.PreviewTextInput += NumberTextBox_PreviewTextInput;
this.TextChanged += NumberTextBox_TextChanged;
}
// 输入限制
private void NumberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!IsValidNumber(e.Text))
{
e.Handled = true;
}
}
private bool IsValidNumber(string input)
{
return Regex.IsMatch(input, "^[0-9]*$");
}
// 数字格式化
private void NumberTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(this.Text))
{
this.Text = int.Parse(this.Text).ToString();
}
}
}
```
在XAML中使用自定义控件:
```xml
<local:NumberTextBox />
```
需要注意的是,上述示例只是一个简单的实现,实际应用中需要根据需求进行更详细的功能设计和实现。