1

I'm trying to set a placeholder on TextBox, I don't know why Microsoft doesn't provide a default property for this control, is very annoying apply a workaround. Anyway, suppose that I've this control:

<TextBox x:Name="Search" />

I've created a separate class to handle all control event. This is the method inside it:

class ControlsHandle
{
    MainWindow main = new MainWindow(); 

    public void RemoveText(object sender, EventArgs e)
    {
        main.Search.Text = "";
    }

    public void AddText(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(main.Search.Text))
            main.Search.Text = "Search a user...";
    }
}

and this is the MainWindow():

public MainWindow()
{
    InitializeComponent();

    Search.GotFocus += GotFocus.EventHandle(ControlsHandle.RemoveText);
    Search.LostFocus += LostFocus.EventHandle(ControlsHandle.AddText);
}

Unfortunately I got this error:

the UIElement.GotFocus event cannot be specified only on the left side of += or -=

on this line: += GotFocus.

Dillinger
  • 1,823
  • 4
  • 33
  • 78
  • just simply add placeholder="Last name" or whatever. placeholders are supported by the browser. You dont have to make any hacks to make it work. Only old browser don't support it. If you need to support old browsers, I would make javascript to support this. – Kiksen Apr 28 '16 at 08:39
  • @Kiksen this is wpf (xaml) not html. Xaml doesn't have a placeholder property – Dillinger Apr 28 '16 at 08:40
  • In that case this is a duplicate :) See: http://stackoverflow.com/questions/11873378/adding-placeholder-text-to-textbox – Kiksen Apr 28 '16 at 08:42
  • You cannot convert a text box to placeholder. According to Microsoft behavior, a text box is one, which alters its own height and width when the text content in it is increased. Whereas a placeholder is a fixed one, it cannot change its size by itself when the text content in it is increased. Only user can be able to modify the width and size of the placeholder. – Arun Prasad Apr 28 '16 at 08:43
  • @ArunPrasad there is no placeholder property that I can use? – Dillinger Apr 28 '16 at 08:44
  • See solution of John Myczek: http://stackoverflow.com/questions/833943/watermark-hint-text-placeholder-textbox-in-wpf – Sebastian Siemens Apr 28 '16 at 08:46
  • @SebastianSchulz too much code for a simple placeholder – Dillinger Apr 28 '16 at 08:47
  • there are some more solutions in the question – Sebastian Siemens Apr 28 '16 at 08:53
  • @Dillinger Try this then: http://stackoverflow.com/questions/11873378/adding-placeholder-text-to-textbox/36909924#36909924 – Dbl Apr 28 '16 at 09:02

1 Answers1

3

Try this

<TextBox Name="search" Text="Search a user..." GotFocus="search_GotFocus"/>

 private void  search_GotFocus(object sender, RoutedEventArgs e)
    {
        search.Text = "";

    }
Irfan
  • 509
  • 2
  • 12