Create a textbox where the text always says MINUTES
I'd like to have a textbox where the content says:
"3 minutes"
But when the person is writing on it, disappears the word minutes and when has lost the focus, again appears the word minutes.
Im develo开发者_如何转开发ping in WPF
A very cut and dry approach that will give you a start to make something better. This doesn't work at all if there isn't any way to lose focus from the textbox (ie. it is the only control on the window)
private void textBox1_GotFocus(object sender, RoutedEventArgs e) {
textBox1.Text = textBox1.Text.Replace(" minutes", "");
}
private void textBox1_LostFocus(object sender, RoutedEventArgs e) {
textBox1.Text = textBox1.Text + " minutes";
}
I assume you are looking to remove the unit
from the textbox OnFocus
and append it when the focus is lost,
private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
TextBox textbox;
if ((textbox = sender as TextBox) != null)
{
// Append the unit if any, otherwise the text remains unchanged
if(textbox.Tag != null)
{
var unit = textbox.Tag.ToString();
if(string.IsNullOrEmpty(unit) == false)
{
textbox.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", textbox.Text, unit);
}
}
}
}
private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textbox;
if((textbox = sender as TextBox) != null)
{
// Note that this assumes values of the type '[value] [units]' (single space delimiter)
var valueAndUnit = textbox.Text.Split(' ');
// If there is a unit then store it to the Tag property
if(valueAndUnit.Length > 1)
{
textbox.Tag = valueAndUnit[1];
}
textbox.Text = valueAndUnit[0];
}
}
Also, take a look are textbox Validation and TextChanged event to santise the text as the user inputs the values (for example, allow only digits to be entered when the value is an integer).
I would do this in javascript with something like like this.
I don't think there's a server side "Focus" event, and I have always thought handling the blur (TextChanged) event server side is bad. I don't want a form to post when my cursor leave a field.
精彩评论