【问题标题】:Xamarin Forms Entry boxes loses their cursor position with custom keypadXamarin 表单输入框使用自定义键盘丢失光标位置
【发布时间】:2020-11-11 06:33:26
【问题描述】:

我正在尝试使用 MVVM 模式创建带有自定义键盘的计算器应用程序。计算器有四个输入框,我通过使用自定义渲染器来抑制手机键盘的显示。我注意到,当我在条目中键入数字时,主菜会丢失光标位置,通过点击另一个位置手动更改光标位置,然后再次开始输入。当我再次开始输入时,初始字符会进入正确的位置,但之后的任何字符都会出现在字符串的开头,这意味着光标位置为零。

我无法弄清楚是什么在重置光标位置。我正在通过绑定跟踪光标位置。这是我下面代码中的一个小sn-p。因此,如果 EntryOne 是 Selected(Has Focus) 并且您开始输入,则调用 GetText 方法并且我通过引用传递光标位置。条目中已存在的文本分为两部分。光标位置前面的所有字符都是第一部分,光标位置之后的所有字符都是第二部分。参数是用户按下的数字。所有三个字符串连接在一起以在“条目”框中显示新文本。如果我使用手机的键盘,我没有这个问题。所以我知道这是可能的。

请查看附加的应用程序,如果需要更多信息,请告诉我。任何帮助将不胜感激。

提前谢谢你!!!

EntryOneText = GetText(EntryOneText, parameter, ref _entryOneCursorIndex);
private string GetText(string text, string parameter, ref int cursorPosition)
{
     if (!string.IsNullOrEmpty(text))
     {
       string partOne = text.Substring(0, cursorPosition);
       string partTwo = text.Substring(cursorPosition, (text.Length - cursorPosition));
       cursorPosition++;
       return string.Format("{0}{1}{2}", partOne, parameter, partTwo);
     }
     cursorPosition++;
     return parameter;
}

EntryCursorPositionTest

【问题讨论】:

  • 手动更改光标位置并设置文本时,条目似乎失去焦点。然后 _entryOneCursorIndex 设置为 0。找到解决方案时会更新您。
  • 谢谢。我期待您的解决方案。
  • 嗯,目前还没有找到解决办法。每次我手动更改光标位置时,_entryOneCursorIndex 都会被重置。调用 GetText 后会发生重置。

标签: xamarin.forms


【解决方案1】:

感谢亚历山德罗·卡利亚罗。他在 Xamarin Forms 论坛上为我提供了答案。

private void EntryOne_Focused(object sender, FocusEventArgs e)
{
  _mainViewModel.SelectedEntry = 1;
  _mainViewModel.EntryOneCursorIndex = ((Entry)sender).CursorPosition;
}

public ICommand NumericCommand
{
  get
  {
    return new Command<string>((string parameter) =>
    {
      if (!string.IsNullOrEmpty(parameter))
      {
        switch (SelectedEntry)
        {
          case 1:
                    if (EntryOneText == null)
                        EntryOneText = "";
                    int save = EntryOneCursorIndex;
                    EntryOneText = EntryOneText.Insert(save, parameter);
                    EntryOneCursorIndex = save + 1;
              //EntryOneText = GetText(EntryOneText, parameter, ref _entryOneCursorIndex);
            break;

【讨论】:

  • 你能接受这个答案吗(点击这个答案左上角的☑️),这将帮助更多有同样问题的人:)。
猜你喜欢
  • 2012-05-21
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
相关资源
最近更新 更多