如何在编辑器Xamarin表单

时间:2016-09-19 11:31:06

标签: xamarin xamarin.forms

如何在 Xamarin表单中的Editor中设置占位符文字占位符颜色

它没有默认的功能或属性如何自定义它?

参考文档: Xamarin Forms Editor

2 个答案:

答案 0 :(得分:3)

您需要一个自定义渲染器(这是Android自定义渲染器),您需要另一个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):

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

Xamarin论坛中已有一个主题: https://forums.xamarin.com/discussion/20616/placeholder-editor

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

答案 1 :(得分:1)

将占位符字符串设置为Xaml中编辑器的文本 然后在Code back file:

InitializeComponent();

var placeholder = myEditor.Text;

myEditor.Focused += (sender, e) =>
{
     // Set the editor's text empty on focus, only if the place 
     // holder is present
     if (myEditor.Text.Equals(placeholder))
     {
          myEditor.Text = string.Empty;
          // Here You can change the text color of editor as well
          // to active text color
     }
};

myEditor.Unfocused += (sender, e) => 
{
     // Set the editor's text to place holder on unfocus, only if 
     // there is no data entered in editor
    if (string.IsNullOrEmpty(myEditor.Text.Trim()))
    {
        myEditor.Text = placeholder;
        // Here You can change the text color of editor as well
        // to dim text color (Text Hint Color)
    }
};