且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在编辑器 Xamarin Forms 中设置占位符和占位符颜色

更新时间:2023-02-03 15:06:06

为此你需要一个自定义渲染器(这里是 Android 自定义渲染器)你需要另一个适用于 iOS 的渲染器:

You will need a custom renderer for that (Here is the Android Custom Renderer) you will need another renderer for iOS:

public class PlaceholderEditor : Editor
{
    public static readonly BindableProperty PlaceholderProperty =
        BindableProperty.Create<PlaceholderEditor, string>(view => view.Placeholder, String.Empty);

    public PlaceholderEditor()
    {
    }

    public string Placeholder
    {
        get
        {
            return (string)GetValue(PlaceholderProperty);
        }

        set
        {
            SetValue(PlaceholderProperty, value);
        }
    }
}

public class PlaceholderEditorRenderer : EditorRenderer
{
    public PlaceholderEditorRenderer()
    {
    }

    protected override void OnElementChanged(
        ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            var element = e.NewElement as PlaceholderEditor;
            this.Control.Hint = element.Placeholder;
        }
    }

    protected override void OnElementPropertyChanged(
        object sender,
        PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == PlaceholderEditor.PlaceholderProperty.PropertyName)
        {
            var element = this.Element as PlaceholderEditor;
            this.Control.Hint = element.Placeholder;
        }
    }
}

对于颜色,您可能需要这样的东西(Android):

And for the color you may need something like this (Android):

Control.SetHintTextColor(Android.Graphics.Color.White);

在 Xamarin 论坛中已经有一个线程:https://forums.xamarin.com/discussion/20616/placeholder-editor

There already a thread for this in the Xamarin Forums: https://forums.xamarin.com/discussion/20616/placeholder-editor

有关自定义渲染器的更多信息如下:https://developer.xamarin.com/guides/xamarin-forms/custom-渲染器/

And more about Custom Renderers information below: https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/