【问题标题】:Get last 3 characters during user typing在用户输入期间获取最后 3 个字符
【发布时间】:2011-01-08 23:43:46
【问题描述】:

当用户在richTextbox中写一些文本时,我需要从richTextBox获取最后三个字符。

我在扩展 WPF 工具包中的 RichTextBox 的 Text 属性上绑定属性。

public string RtbText
{
    get { return _rtbText; }
    set
    {
        _rtbText = value;
        NotifyPropertyChanged("RtbText");
    }
}

我使用 Reactive Extensions for .NET (Rx) 并在属性 RtbText 上创建 Observer

    Observable.FromEvent<PropertyChangedEventArgs>(this, "PropertyChanged")
        .Where(e => e.EventArgs.PropertyName == "RtbText")
        .Select(_ => this.RtbText)
        .Where(text => text.Length > 1)
        .Do(AddSmiles)
        .Throttle(TimeSpan.FromSeconds(1))
        .Subscribe(GetLastThreeChars);

   private void GetLastThreeChars(string text)
   {
       if (text.Length > 3)
       {
           string lastThreeChars = text.Substring(text.Length - 2, text.Length);
       }
   }

但是如果我开始输入richTextBox,我会得到这个异常:

索引和长度必须引用字符串中的位置。
参数名称:长度

在 System.String.InternalSubStringWithChecks(Int32 startIndex,Int32 长度,布尔 fAlwaysCopy)
在 System.String.Substring(Int32 startIndex, Int32 长度)
在 C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger\ver.beta\IoC.Get\Pokec_Messenger\ver.beta\Pokec_Messenger\ 中的 WpfApplication1.MainWindow.GetLastThreeChars(字符串文本) WpfApplication1\MainWindow.xaml.cs:第 97 行
在 System.Linq.Observable.c
_DisplayClass389`1.c_DisplayClass38b.b_388(TSource x)

【问题讨论】:

    标签: wpf string richtextbox system.reactive


    【解决方案1】:

    如果text.Length &gt; 3(假设是 4)那么:

    text.Length - 2 = 2
    

    所以你的代码是:

    string lastThreeChars = text.Substring(2, 4);
    

    这将失败,因为您在子字符串中要求 四个 字符,这使其超出范围。

    String.Substring Method (Int32, Int32)

    从此实例中检索子字符串。子字符串从指定的字符位置开始,并具有指定的长度

    另外,您的测试和起始位置不正确。不要忘记 C# 数组和字符串是零索引的。检查长度严格大于 3 的情况,当您想要返回整个字符串时,您会错过用户输入恰好三个字符的情况。

    您的代码需要:

    if (text.Length > 2)
    {
        string lastThreeChars = text.Substring(text.Length - 3, 3);
    }
    

    如果你不需要指定长度:

    if (text.Length > 2)
    {
        string lastThreeChars = text.Substring(text.Length - 3);
    }
    

    将返回字符串中的最后三个字符。

    【讨论】:

      【解决方案2】:

      这是另一种形式。它将所有字符从某个开始位置到结束

      string lastThreeChars = text.Substring(text.Length - 3);
      

      也许是 text.Length - 2. 未经测试

      【讨论】:

        猜你喜欢
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-18
        • 2020-03-23
        • 2018-03-14
        • 2023-02-08
        相关资源
        最近更新 更多