【问题标题】:Xamarin Forms get cursor position in editor controlXamarin Forms 在编辑器控件中获取光标位置
【发布时间】:2021-09-28 20:18:36
【问题描述】:

如何获取编辑器控件内的光标位置?

我一直在寻找答案,但我能找到的最好的是 Cursor 类,但这似乎在 xamarin 中不存在。

【问题讨论】:

标签: c# xamarin xamarin.forms


【解决方案1】:

您可以自定义一个编辑器,并使用custom renderer 获取SelectionPositionSelectionPosition

在您的 fomrs 项目中自定义一个 FormEditor

public class FormEditor:Editor
{
    public int SelectionPosition;

    public EventHandler SelectChanageEvent { get; set; }
}

在您的 Android 项目中创建 AndroidEditor

class AndroidEditor : EditorRenderer, EditTextSelectChange
{
    private Context mContext;

    public AndroidEditor(Context context) : base(context)
    {
        mContext = context;
    }

    public void Change(int lastPos, int curPos)
    {

        ((FormEditor)Element).SelectionPosition = curPos;
        ((FormEditor)Element).SelectChanageEvent.Invoke(this, null);
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
        MyEditText myEditText = new MyEditText(mContext);
        myEditText.SetEditTextSelectChange(this);
        SetNativeControl(myEditText);

    }
}

在您的 Android 项目中自定义 MyEditText

public class MyEditText : FormsEditText
{

    private int mLastPos = 0;
    private int mCurPos = 0;
    private EditTextSelectChange editTextSelectChange;

    public void SetEditTextSelectChange(EditTextSelectChange editTextSelectChange)
    {
        this.editTextSelectChange = editTextSelectChange;
    }
    public MyEditText(Context context) : base(context)
    {
    }


    protected override void OnSelectionChanged(int selStart, int selEnd)
    {
        base.OnSelectionChanged(selStart, selEnd);
        if (editTextSelectChange != null)
        {
            mCurPos = selEnd;
            editTextSelectChange.Change(mLastPos, mCurPos);
            mLastPos = mCurPos;
        }
    }
    public interface EditTextSelectChange
    {
        void Change(int lastPos, int curPos);
    }
}

然后在你的 page.xaml 中使用:

 <local:FormEditor x:Name="editor" Placeholder="Hello"></local:FormEditor>

在您的 page.xaml.cs 中:

public YourPage()
  {
        InitializeComponent();
        editor.SelectChanageEvent += SelectEvent;
  }

  
  private void SelectEvent(object sender, EventArgs e)
  {
     // you could get the Curson Position by editor.SelectionPosition
     Console.WriteLine("curPos = {0}", editor.SelectionPosition);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多