当用户在文本框中输入ssn时添加破折号。无法使用delete\backbutton删除hyphons [英] Add dashes when user is entering ssn in a text box.unable to delete hyphons using delete\backbutton
本文介绍了当用户在文本框中输入ssn时添加破折号。无法使用delete\backbutton删除hyphons的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户在文本框中输入ssn时,我有一个XAML要求添加破折号。我尝试下面的代码,能够添加短划线,但无法从文本框中删除破折号。每当我尝试删除或使用后退空间连字符都不会被删除
我尝试过:
XAML:
Hi I have a XAML requirement to add dashes when user is entering ssn in a text box. I tried below code, am able to add dashes, but unable to delete dashes from text box. Whenever i try to delete or use back space hyphens are not deleted
What I have tried:
XAML:
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,10,0,0"
TextWrapping="Wrap" Name="Txtssn"
Text=""
MaxLength="11"
VerticalAlignment="Top"
Width="120"
TextChanged="TextBox_TextChanged"/>
C#:
C#:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
string data = textBox.Text;
if (data.Length == 3)
{
string formattedSSN = data.Insert(3, "-");
Txtssn.Text = formattedSSN.ToString();
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}
else if (data.Length == 6)
{
string formattedSSN = data.Insert(6, "-");
Txtssn.Text = formattedSSN.ToString();
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}}}
推荐答案
为了正确添加或删除你应该处理的连字符,例如< a href =https://msdn.microsoft.com/en-us/library/system.windows.uielement.keydown(v=vs.110).aspx> UIElement.KeyDown事件(System.Windows) [ ^ ]。在事件处理程序中,检查用户是否正在添加文本或将其删除(按下退格键)。此外,您还需要考虑是否按下删除键和/或是否选择了文本区域和文本中的插入位置。
有相当的几个例子,如如何实施WPF中文本框的掩码 [ ^ ]。但是,也许最简单的方法是使用扩展WPF工具包的现成控件[ ^ ]
In order to correctly add or remove the hyphen you should handle for example UIElement.KeyDown Event (System.Windows)[^] . In the event handler, check if the user is adding text or removing it (backspace pressed). Also you need to take into consideration if delete key is pressed and/or if an area of text is selected and the caret position in the text.
There are quite a few example, like How To Implement a Mask for a Text Box in W.P.F.[^]. However, perhaps the easiest way would be to use a ready made control from Extended WPF Toolkit™[^]
这篇关于当用户在文本框中输入ssn时添加破折号。无法使用delete\backbutton删除hyphons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文