1

I was looking around on how to do a placeholder on WPF, and I found this answer (the first one).

The code given in the answer is here:

        TextBox myTxtbx = new TextBox();
        myTxtbx.Text = "Enter text here...";

        myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
        myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

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

        void AddText(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(myTxtbx.Text))
                myTxtbx.Text = "Enter text here...";
        }

When I enter in my code, I get the following error:

The event 'UIElement.GotFocus' can only appear on the left hand side of += or -=

The event 'UIElement.LostFocus' can only appear on the left hand side of += or -=

I know what the error means, but I'm not sure what to do to fix the error and still get the desired result. Help would be greatly appreciated!

Community
  • 1
  • 1

1 Answers1

0

Ok, here is a complete code sample for you. I have created 2 Textboxes, One to show placeholder and another to call lost focus event. You can remove 2nd Textbox if you have any other control which could help Textbox 1 to call Lost focus event. Then AddText and RemoveText methods, which are fairly simple. let me know if you need any more details on this:

XAML

<StackPanel Name="sp1" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</StackPanel>

CODE

        TextBox myTxtbx;
        public MainWindow()
        {
            InitializeComponent();               
            TextBox myTxtbx = new TextBox();
            TextBox myTxtbx1 = new TextBox();
            myTxtbx.Height = 50;
            myTxtbx.Width = 100;
            myTxtbx1.Height = 50;
            myTxtbx1.Width = 100;
            myTxtbx.Text = "Enter text here...";
            myTxtbx.Text = "I am here just to help call lost focus";
            myTxtbx.GotFocus += MyTxtbx_GotFocus1;
            myTxtbx.LostFocus += MyTxtbx_LostFocus;

            sp1.Children.Add(myTxtbx); //Sp1 is any layout control in which you want to add your textbox, In my case I have stackpanel.
            sp1.Children.Add(myTxtbx1);
        }

        private void MyTxtbx_LostFocus(object sender, RoutedEventArgs e)
        {
            var a = sender as TextBox;
            if (String.IsNullOrWhiteSpace(a.Text))
                a.Text = "Enter text here...";
        }

        private void MyTxtbx_GotFocus1(object sender, RoutedEventArgs e)
        {
            var a = sender as TextBox;
            a.Text = "";
        }
Naresh Ravlani
  • 1,600
  • 13
  • 28