Может ли кто-нибудь указать мне на хорошую реализацию базового текстового поля Windows Forms TextBox, который изначально отобразит текст водяного знака, который исчезнет, когда курсор войдет в него? Я думаю, что могу создать свое собственное творческое использование событий "Ввод и выключение", но я уверен, что там где-то есть идеальная реализация. Я видел реализацию WPF, и в случае необходимости я мог ее вложить, но родной WinForms TextBox был бы лучше.
У меня это до сих пор; еще не пробовал, но кто-нибудь видит какие-либо вопиющие проблемы?
public class WatermarkTextBox:TextBox
{
public string WatermarkText { get; set; }
public Color WatermarkColor { get; set; }
private Color TextColor { get; set; }
private bool isInTransition;
public WatermarkTextBox()
{
WatermarkColor = SystemColors.GrayText;
}
private bool HasText { get { return Text.IsNotNullOrBlankOr(WatermarkText); }}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
if (HasText) return;
isInTransition = true;
ForeColor = TextColor;
Text = String.Empty;
isInTransition = false;
}
protected override void OnForeColorChanged(EventArgs e)
{
base.OnForeColorChanged(e);
if (!isInTransition) //the change came from outside
TextColor = ForeColor;
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
if (HasText) return;
isInTransition = true;
ForeColor = WatermarkColor;
Text = WatermarkText.EmptyIfNull();
isInTransition = false;
}
}
РЕДАКТОР: вышеизложенное в конечном итоге сработало бы с некоторой утонченностью, но CueProvider работал намного лучше. Здесь моя окончательная реализация:
public class WatermarkTextBox:TextBox
{
private string watermarkText;
public string WatermarkText
{
get { return watermarkText; }
set
{
watermarkText = value;
if (watermarkText.IsNullOrBlank())
CueProvider.ClearCue(this);
else
CueProvider.SetCue(this, watermarkText);
}
}
}
Я мог бы полностью интегрировать функции CueProvider, но это прекрасно работает.