在文本框中每隔4个字符自动插入连字符

在文本框中每隔4个字符自动插入连字符

本文介绍了在文本框中每隔4个字符自动插入连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一些功能,当用户输入4个字符时,应在文本中添加连字符,然后用户再次输入4个字符,然后应再次在WPF中自动添加连字符.

I want to implement some thing that when a user enters 4 characters then a hyphen should be added to the text and then again user enter 4 characters and then again hypen should added automatically in WPF.

注意

我想在用户在文本框中键入内容时实现这种行为(不是在文本框失去焦点之后),因为后者很容易实现"

使用MVVM模型,因此Dialog后面的代码应该为空

推荐答案

属性定义:我们应该计算字符串中不包含连字符的字符由于尚未调用 OnPropertyChanged ,因此无法在此处设置插入符号索引,因此 TextBox.Text stil包含旧值,并且您不能设置大于文本的值长度:

Property Definition : we should count the characters in the string not including the hyphens Caret index cant be set here because OnPropertyChanged is not being invoked yet, so the TextBox.Text stil contains the old value, and you cant set a value which bigger than the text length:

 private string _serial;
 public string Serial
 {
     get { return _serial; }
     set
     {
         if (_serial != value)
         {
             _serial = value;
             int res = 0;
             int hyphensCount = _serial.Count(c => c.Equals('-'));
             Math.DivRem(_serial.Length - hyphensCount, 4, out res);
             if (res == 0)
                 _serial = string.Format("{0}-", _serial);
             OnPropertyChanged("Serial");
         }
     }
 }

行为-注册到 TextChanged 事件,然后将插入符号移动到文本的结尾:

Behavior - register to TextChanged event and move the caret to the end of text:

 public class MoveCaretToEndBehavior: Behavior<TextBox>
{
    protected override void OnAttached()
    {
        AssociatedObject.TextChanged += new TextChangedEventHandler(AssociatedObject_TextChanged);
    }

    void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
    {
        AssociatedObject.CaretIndex = AssociatedObject.Text.Length;
    }
}

文本框+行为

<TextBox Text="{Binding Serial,UpdateSourceTrigger=PropertyChanged}">
        <i:Interaction.Behaviors>
            <local:MoveCaretToEndBehavior />
        </i:Interaction.Behaviors>


</TextBox>

这篇关于在文本框中每隔4个字符自动插入连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:23