texto sirven que power posición posicion para nuevo marcadores marcador los fuente forma eliminar cuadro añadir c# wpf placeholder

c# - posición - para que sirven los marcadores de audio en power point



Agregar texto de marcador de posición al cuadro de texto (19)

¿No sería eso algo como esto?

Textbox myTxtbx = new Textbox(); myTxtbx.Text = "Enter text here..."; myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText); myTxtbx.LostFocus += LostFocus.EventHandle(AddText); public RemoveText(object sender, EventArgs e) { myTxtbx.Text = ""; } public AddText(object sender, EventArgs e) { if(String.IsNullOrWhiteSpace(myTxtbx.Text)) myTxtbx.Text = "Enter text here..."; }

Eso es solo un pseudocódigo, pero el concepto está ahí.

Estoy buscando una forma de agregar texto de marcador de posición a un cuadro de texto como se puede con un cuadro de texto en html5.

Es decir, si el cuadro de texto no tiene texto, agrega el texto Enter some text here , cuando el usuario hace clic en él, el texto del marcador de posición desaparece y permite al usuario ingresar su propio texto, y si el cuadro de texto pierde el foco y todavía no hay texto luego, el marcador de posición se agrega al cuadro de texto.


Agregue esta clase a su proyecto y construya su solución. Haga clic en Toolbox en Visual Studio verá un nuevo componente de cuadro de texto llamado PlaceholderTextBox. Elimine su cuadro de texto actual en el formulario designado y reemplácelo con PlaceHolderTextBox.

PlaceHolderTextBox tiene una propiedad PlaceHolderText. Establezca el texto que desee y tenga un buen día :)

public class PlaceHolderTextBox : TextBox { bool isPlaceHolder = true; string _placeHolderText; public string PlaceHolderText { get { return _placeHolderText; } set { _placeHolderText = value; setPlaceholder(); } } public new string Text { get => isPlaceHolder ? string.Empty : base.Text; set => base.Text = value; } //when the control loses focus, the placeholder is shown private void setPlaceholder() { if (string.IsNullOrEmpty(base.Text)) { base.Text = PlaceHolderText; this.ForeColor = Color.Gray; this.Font = new Font(this.Font, FontStyle.Italic); isPlaceHolder = true; } } //when the control is focused, the placeholder is removed private void removePlaceHolder() { if (isPlaceHolder) { base.Text = ""; this.ForeColor = System.Drawing.SystemColors.WindowText; this.Font = new Font(this.Font, FontStyle.Regular); isPlaceHolder = false; } } public PlaceHolderTextBox() { GotFocus += removePlaceHolder; LostFocus += setPlaceholder; } private void setPlaceholder(object sender, EventArgs e) { setPlaceholder(); } private void removePlaceHolder(object sender, EventArgs e) { removePlaceHolder(); } }


Aquí vengo con esta solución inspirada en @Kemal Karadag.

Noté que cada solución publicada aquí depende del enfoque,

Si bien quería que mi marcador de posición fuera el clon exacto de un marcador de posición HTML estándar en Google Chrome.

En lugar de ocultar / mostrar el marcador de posición cuando la caja está enfocada,

Oculto / muestro el marcador de posición dependiendo de la longitud del texto de la caja:

Si el cuadro está vacío, se muestra el marcador de posición, y si escribe en el cuadro, el marcador de posición desaparece.

¡Como se hereda de un TextBox estándar, puedes encontrarlo en tu Toolbox!

using System; using System.Drawing; using System.Windows.Forms; public class PlaceHolderTextBox : TextBox { private bool isPlaceHolder = true; private string placeHolderText; public string PlaceHolderText { get { return placeHolderText; } set { placeHolderText = value; SetPlaceholder(); } } public PlaceHolderTextBox() { TextChanged += OnTextChanged; } private void SetPlaceholder() { if (!isPlaceHolder) { this.Text = placeHolderText; this.ForeColor = Color.Gray; isPlaceHolder = true; } } private void RemovePlaceHolder() { if (isPlaceHolder) { this.Text = this.Text[0].ToString(); // Remove placeHolder text, but keep the character we just entered this.Select(1, 0); // Place the caret after the character we just entered this.ForeColor = System.Drawing.SystemColors.WindowText; isPlaceHolder = false; } } private void OnTextChanged(object sender, EventArgs e) { if (this.Text.Length == 0) { SetPlaceholder(); } else { RemovePlaceHolder(); } } }


Basado en la respuesta de ExceptionLimeCat, una mejora:

Color farbe; string ph = "Placeholder-Text"; private void Form1_Load(object sender, EventArgs e) { farbe = myTxtbx.ForeColor; myTxtbx.GotFocus += RemoveText; myTxtbx.LostFocus += AddText; myTxtbx.Text = ph; } public void RemoveText(object sender, EventArgs e) { myTxtbx.ForeColor = farbe; if (myTxtbx.Text == ph) myTxtbx.Text = ""; } public void AddText(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(myTxtbx.Text)) { myTxtbx.ForeColor = Color.Gray; myTxtbx.Text = ph; } }


En lugar de manejar el foco, ingrese y enfoque deje eventos para establecer y eliminar el texto de marcador de posición. Es posible usar la función Enviar mensaje de Windows para enviar el mensaje EM_SETCUEBANNER a nuestro cuadro de texto para que hagamos el trabajo por nosotros.

Esto se puede hacer con dos sencillos pasos. Primero, debemos exponer la función Windows SendMessage .

private const int EM_SETCUEBANNER = 0x1501; [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);

Luego simplemente llame al método con el control de nuestro cuadro de texto, el valor de EM_SETCUEBANNER y el texto que queremos establecer.

SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "Username"); SendMessage(textBox2.Handle, EM_SETCUEBANNER, 0, "Password");

Referencia: establecer texto de marcador de posición para el cuadro de texto (texto de referencia)


En lugar de usar la propiedad .Text de un TextBox, superpuse un TextBlock con el marcador de posición. No pude usar la propiedad .Text porque estaba enlazada a un evento.

XAML:

<Canvas Name="placeHolderCanvas"> <TextBox AcceptsReturn="True" Name="txtAddress" Height="50" Width="{Binding ActualWidth, ElementName=placeHolderCanvas}" Tag="Please enter your address"/> </Canvas>

VB.NET

Public Shared Sub InitPlaceholder(canvas As Canvas) Dim txt As TextBox = canvas.Children.OfType(Of TextBox).First() Dim placeHolderLabel = New TextBlock() With {.Text = txt.Tag, .Foreground = New SolidColorBrush(Color.FromRgb(&H77, &H77, &H77)), .IsHitTestVisible = False} Canvas.SetLeft(placeHolderLabel, 3) Canvas.SetTop(placeHolderLabel, 1) canvas.Children.Add(placeHolderLabel) AddHandler txt.TextChanged, Sub() placeHolderLabel.Visibility = If(txt.Text = "", Visibility.Visible, Visibility.Hidden) End Sub

Resultado:


Este no es mi código, pero lo uso mucho y funciona perfecto ... XAML SOLAMENTE

<TextBox x:Name="Textbox" Height="23" Margin="0,17,18.8,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" HorizontalAlignment="Right" ></TextBox> <TextBlock x:Name="Placeholder" IsHitTestVisible="False" TextWrapping="Wrap" Text="Placeholder Text" VerticalAlignment="Top" Margin="0,20,298.8,0" Foreground="DarkGray" HorizontalAlignment="Right" Width="214"> <TextBlock.Style> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding Text, ElementName=Textbox}" Value=""> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock>


Esto significa que tiene un botón que le permite realizar una acción, como iniciar sesión o algo así. Antes de realizar la acción, verifique si el cuadro de texto está lleno. De lo contrario, reemplazará el texto.

private void button_Click(object sender, EventArgs e) { string textBoxText = textBox.Text; if (String.IsNullOrWhiteSpace(textBoxText)) { textBox.Text = "Fill in the textbox"; } } private void textBox_Enter(object sender, EventArgs e) { TextBox currentTextbox = sender as TextBox; if (currentTextbox.Text == "Fill in the textbox") { currentTextbox.Text = ""; } }

Es cursi, pero revisar el texto por el valor que le das es lo mejor que puedo hacer, no tan bueno en c # para obtener una mejor solución.


Propiedades adjuntas al rescate:

public static class TextboxExtensions { public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached( "Placeholder", typeof(string), typeof(TextboxExtensions), new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)); private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { var tb = dependencyObject as TextBox; if(tb == null) return; tb.LostFocus -= OnLostFocus; tb.GotFocus -= OnGotFocus; if (args.NewValue != null) { tb.GotFocus += OnGotFocus; tb.LostFocus += OnLostFocus; } } private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs) { var tb = sender as TextBox; if (string.IsNullOrEmpty(tb.Text) || string.IsNullOrWhiteSpace(tb.Text)) { tb.Text = GetPlaceholder(tb); } } private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs) { var tb = sender as TextBox; var ph = GetPlaceholder(tb); if (tb.Text == ph) { tb.Text = string.Empty; } } [AttachedPropertyBrowsableForType(typeof(TextBox))] public static void SetPlaceholder(DependencyObject element, string value) { element.SetValue(PlaceholderProperty, value); } [AttachedPropertyBrowsableForType(typeof(TextBox))] public static string GetPlaceholder(DependencyObject element) { return (string) element.GetValue(PlaceholderProperty); } }

Uso:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>


Pruebe el siguiente código:

<TextBox x:Name="InvoiceDate" Text="" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" /> <TextBlock IsHitTestVisible="False" Text="Men att läsa" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Padding="5, 5, 5, 5" Foreground="LightGray"> <TextBlock.Style> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding Text, ElementName=InvoiceDate}" Value=""> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding ElementName=InvoiceDate, Path=IsFocused}" Value="True"> <Setter Property="Visibility" Value="Collapsed"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock>


Puede obtener la Template predeterminada , modificarla superponiendo un TextBlock y usar un Style para agregar activadores que lo oculten y lo muestren en los estados correctos.


Puedes usar esto, es trabajo para mí y es una solución extremadamente simple.

<Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Grid> <TextBox Text="{Binding Path=Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" x:Name="textSource" Background="Transparent" Panel.ZIndex="2" /> <TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1"> <TextBox.Style> <Style TargetType="{x:Type TextBox}"> <Setter Property="Foreground" Value="Transparent"/> <Style.Triggers> <DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value=""> <Setter Property="Foreground" Value="LightGray"/> </DataTrigger> </Style.Triggers> </Style> </TextBox.Style> </TextBox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

Uso:

<TextBox Style="{StaticResource placeHolder}" Tag="Name of customer" Width="150" Height="24"/>


Se me ocurrió un método que funcionó para mí, pero solo porque estaba dispuesto a usar el nombre del cuadro de texto como marcador de posición. Vea abajo.

public TextBox employee = new TextBox(); private void InitializeHomeComponent() { // //employee // this.employee.Name = "Caller Name"; this.employee.Text = "Caller Name"; this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder; this.employee.Location = new System.Drawing.Point(5, 160); this.employee.Size = new System.Drawing.Size(190, 30); this.employee.TabStop = false; this.Controls.Add(employee); // I loop through all of my textboxes giving them the same function foreach (Control C in this.Controls) { if (C.GetType() == typeof(System.Windows.Forms.TextBox)) { C.GotFocus += g_GotFocus; C.LostFocus += g_LostFocus; } } } private void g_GotFocus(object sender, EventArgs e) { var tbox = sender as TextBox; tbox.Text = ""; } private void g_LostFocus(object sender, EventArgs e) { var tbox = sender as TextBox; if (tbox.Text == "") { tbox.Text = tbox.Name; } }


Si bien el uso del mensaje EM_SETCUEBANNER es probablemente el más simple, una cosa que no me gusta es que el texto del marcador de posición desaparece cuando el control se enfoca. Esa es una de mis preocupaciones cuando estoy llenando formularios. Debo hacer clic para recordar para qué sirve el campo.

Entonces aquí hay otra solución para WinForms. Superpone una Label en la parte superior del control, que desaparece solo cuando el usuario comienza a escribir.

Ciertamente no es a prueba de balas. Acepta cualquier Control , pero solo lo he probado con un TextBox . Puede necesitar modificaciones para trabajar con algunos controles. El método devuelve el control Label en caso de que necesite modificarlo un poco en un caso específico, pero puede que nunca sea necesario.

Úselo así:

SetPlaceholder(txtSearch, "Type what you''re searching for");

Este es el método:

/// <summary> /// Sets placeholder text on a control (may not work for some controls) /// </summary> /// <param name="control">The control to set the placeholder on</param> /// <param name="text">The text to display as the placeholder</param> /// <returns>The newly-created placeholder Label</returns> public static Label SetPlaceholder(Control control, string text) { var placeholder = new Label { Text = text, Font = control.Font, ForeColor = Color.Gray, BackColor = Color.Transparent, Cursor = Cursors.IBeam, Margin = Padding.Empty, //get rid of the left margin that all labels have FlatStyle = FlatStyle.System, AutoSize = false, //Leave 1px on the left so we can see the blinking cursor Size = new Size(control.Size.Width - 1, control.Size.Height), Location = new Point(control.Location.X + 1, control.Location.Y) }; //when clicking on the label, pass focus to the control placeholder.Click += (sender, args) => { control.Focus(); }; //disappear when the user starts typing control.TextChanged += (sender, args) => { placeholder.Visible = string.IsNullOrEmpty(control.Text); }; //stay the same size/location as the control EventHandler updateSize = (sender, args) => { placeholder.Location = new Point(control.Location.X + 1, control.Location.Y); placeholder.Size = new Size(control.Size.Width - 1, control.Size.Height); }; control.SizeChanged += updateSize; control.LocationChanged += updateSize; control.Parent.Controls.Add(placeholder); placeholder.BringToFront(); return placeholder; }


También podrías intentarlo de esta manera ...

llamar a la función

TextboxPlaceHolder(this.textBox1, "YourPlaceHolder");

escribe esta función

private void TextboxPlaceHolder(Control control, string PlaceHolderText) { control.Text = PlaceHolderText; control.GotFocus += delegate (object sender, EventArgs args) { if (cusmode == false) { control.Text = control.Text == PlaceHolderText ? string.Empty : control.Text; //IF Focus TextBox forecolor Black control.ForeColor = Color.Black; } }; control.LostFocus += delegate (object sender, EventArgs args) { if (string.IsNullOrWhiteSpace(control.Text) == true) { control.Text = PlaceHolderText; //If not focus TextBox forecolor to gray control.ForeColor = Color.Gray; } }; }


También puede hacer eso cuando el mouse hace clic, supongamos que su marcador de posición es "User_Name"

private void textBox1_MouseClick(object sender, MouseEventArgs e) { if(textBox1.Text == "User_Name") textBox1.Text = ""; }


txtUsuario.Attributes.Add ("marcador de posición", "Texto");


public void Initialize() { SetPlaceHolder(loginTextBox, " Логин "); SetPlaceHolder(passwordTextBox, " Пароль "); } public void SetPlaceHolder(Control control, string PlaceHolderText) { control.Text = PlaceHolderText; control.GotFocus += delegate(object sender, EventArgs args) { if (control.Text == PlaceHolderText) { control.Text = ""; } }; control.LostFocus += delegate(object sender, EventArgs args){ if (control.Text.Length == 0) { control.Text = PlaceHolderText; } }; }


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace App_name { public class CustomTextBox : TextBox { private string Text_ = ""; public CustomTextBox() : base() {} public string setHint { get { return Text_; } set { Text_ = value; } } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); if (Text_.Equals(this.Text)) this.Clear(); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); if (String.IsNullOrWhiteSpace(this.Text)) this.Text = Text_; } } } > xmlns:local="clr-namespace:app_name" > <local:CustomTextBox > x:Name="id_number_txt" > Width="240px" > Height="auto"/>