Как установить Placeholder и PlaceHolder Color в редакторе Xamarin Forms
Как установить заполнитель текста и цвет заполнителя в Editor
в формах Xamarin.
Он не имеет функциональности по умолчанию или свойств, как его настроить?
Справочная документация: Xamarin Forms Editor
2 ответа
Решение
Для этого вам понадобится пользовательский рендер (здесь Android Custom Renderer), вам понадобится другой рендер для 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/
Установите строку-заполнитель для текста вашего редактора в Xaml Затем в коде позади файла:
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)
}
};