光标一直向左跳(到开头)

问题描述 投票:0回答:1

我正在尝试添加不同的行为和转换器。但无论我在做什么,光标都会回到开头。

例如,我尝试使用行为来防止连续出现超过 1 个空格。

因此,当用户输入超过 1 个空格(连续)时,应删除第二个空格并仅保留 1 个空格 (

text.Replace("  ", " ")
),并且光标应停留在其位置。 但相反,光标跳回到开头。 它也以不同的行为来做到这一点。

如果用户输入“This is Nice”,如何使光标保持在其位置。它将是“这很好”(而不是“这很好”)。

我希望我的解释是正确的。 非常感谢。

我刚刚创建了一个新的应用程序(仍在做同样的事情) 这是我的代码

xaml:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TestProj.Behaviors"
             x:Class="TestProj.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Entry Placeholder="Hello">
                <Entry.Behaviors>
                    <local:WhiteSpaceBehavior />
                </Entry.Behaviors>
            </Entry>

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

行为类别:

namespace TestProj.Behaviors {
    public class WhiteSpaceBehavior : Behavior<Entry>
    {
        protected override void OnAttachedTo(Entry entry)
        {
            base.OnAttachedTo(entry);
            entry.TextChanged += OnEntryTextChanged;
        }

        protected override void OnDetachingFrom(Entry entry)
        {
            entry.TextChanged -= OnEntryTextChanged;
            base.OnDetachingFrom(entry);
        }

        private void OnEntryTextChanged(object sender, TextChangedEventArgs e)
        {
            var entry = (Entry)sender;
            var newText = e.NewTextValue;

            if (ContainsConsecutiveWhiteSpaces(newText))
            {
                newText = RemoveConsecutiveWhiteSpaces(newText);
                entry.Text = newText;
            }
        }

        private bool ContainsConsecutiveWhiteSpaces(string text)
        {
            for (int i = 0; i < text.Length - 1; i++)
            {
                if (char.IsWhiteSpace(text[i]) && char.IsWhiteSpace(text[i + 1]))
                {
                    return true;
                }
            }
            return false;
        }

        private string RemoveConsecutiveWhiteSpaces(string text)
        {
            var newText = text.Replace("  ", " ");
            if (newText.Contains("  "))
            {
                newText = RemoveConsecutiveWhiteSpaces(newText);
            }
            return newText;
        }
    }
 }
xaml xamarin.forms maui
1个回答
0
投票

我无法重现您所描述的问题,但您可以通过设置

CursorPosition
:

来强制光标位置保持在末尾
private void OnEntryTextChanged(object sender, TextChangedEventArgs e)
        {
   var entry = (Entry)sender;
   var newText = e.NewTextValue;

   if (ContainsConsecutiveWhiteSpaces(newText))
   {
       newText = RemoveConsecutiveWhiteSpaces(newText);
       entry.Text = newText;
       entry.CursorPosition = newText.Length;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.