using System.Windows; using System.Windows.Controls; namespace TranslatorByMoth { public class TextBoxWithPrompt : TextBox { private string _textPrompt; private bool _isUsingPrompt; private TextAlignment _normalTextAlignment = TextAlignment.Left; private TextAlignment _promptTextAlignment = TextAlignment.Center; private FontStyle _normalFontStyle = FontStyles.Normal; private FontStyle _promptFontStyle = FontStyles.Italic; private bool IsUsingPrompt { get { return _isUsingPrompt; } set { _isUsingPrompt = value; if (_isUsingPrompt) { this.FontStyle = this.PromptFontStyle; this.TextAlignment = this.PromptTextAlignment; } else { this.FontStyle = this.NormalFontStyle; this.TextAlignment = this.NormalTextAlignment; } } } protected override void OnGotFocus(RoutedEventArgs e) { if (this.IsUsingPrompt) { this.IsUsingPrompt = false; this.Text = string.Empty; } base.OnGotFocus(e); } protected override void OnLostFocus(RoutedEventArgs e) { if (this.Text.Trim().Length == 0 || this.Text.Trim() == this.TextPrompt) { this.IsUsingPrompt = true; this.Text = this.TextPrompt; } base.OnLostFocus(e); } // Set this property and then follow it with a call to the MyText setter public string TextPrompt { get { return _textPrompt; } set { this.IsUsingPrompt = value.Length > 0; // let it throw if null _textPrompt = value; } } // Use this externally instead of Text public string MyText { get { if (this.IsUsingPrompt || this.Text.Trim().Length == 0) { return string.Empty; } return this.Text; } set { if (value == null) { value = string.Empty; } if (this.IsUsingPrompt && (value.Trim().Length > 0 && value != this.TextPrompt)) { this.IsUsingPrompt = false; } if (value.Trim().Length == 0 && this._textPrompt.Length > 0) //&& !this.Focused { this.IsUsingPrompt = true; this.Text = this.TextPrompt; return; } this.Text = value; } } // Styles for prompt and normal public TextAlignment NormalTextAlignment { get { return _normalTextAlignment; } set { _normalTextAlignment = value; if (!_isUsingPrompt) this.TextAlignment = value; } } public TextAlignment PromptTextAlignment { get { return _promptTextAlignment; } set { _promptTextAlignment = value; if (_isUsingPrompt) this.TextAlignment = value; } } public FontStyle NormalFontStyle { get { return _normalFontStyle; } set { _normalFontStyle = value; if (!_isUsingPrompt) this.FontStyle = value; } } public FontStyle PromptFontStyle { get { return _promptFontStyle; } set { _promptFontStyle = value; if (_isUsingPrompt) this.FontStyle = value; } } } }