WPF SelectAll on focus TextBox

20 בJanuary 2013

תגיות:
אין תגובות


The problem I will Present now is a good demonstration about WPF and the
way there Controls acting as default.

Let say that I have textbox in my window and I want to select the all
text (if exist)

In case of  focus. Well, what kind
of focus we got?

a.     
By using the auto tab
Keyboard pressed what moving the auto focus one

By one all the way in our controls.

b.     
Using something like
FocusManger or directly called ControlX.focus();

In those 2 cases its fine to tell the textbox
to select all inner text.

c.     
Another kind of focus is by
using our mouse cursor  to access the

Control writing field.  in this case even if we order the textbox explicitly
 

To select all is text it will not respond..  let says in case like this:

GotFocus=”TextBox1_OnGotFocus”

 private
void TextBox1_OnGotFocus(object sender, RoutedEventArgs
e)

        {

           
textBox1.SelectAll();

        }

or this:   MouseLeftButtonDown=”TextBox1_OnMouseLeftButtonDown”

private void
TextBox1_OnMouseLeftButtonDown

                              (object sender, MouseButtonEventArgs
e)

        {

           
textBox1.SelectAll();

        }

The fact is on the last
option that we don’t even gonna see if the method got called since WPF textbox
(and others like passwordBox) has default behavior for mouse left click on
inner text field because the default is to writing in the field ,

Ok. That
for WPF bring us another Event and we call him
PreviewMouseLeftButtonDown

This is a
good start but even inside the implementation if we try to activate the select
all method it will not happened, since again those controls got their on
implementation to deal with the event so what ever we will try to do inside if
is about the default behavior of the control we must adding the next command:

 e.Handled = true;

and its about to tell
the system: “ok this Event is on my responsibility”the full
eventHandller code will looks like that:

  private
void TextBox1_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs
e)

        {

            if (!string.IsNullOrEmpty(textBox1.Text))

            {

               
textBox1.SelectAll();

                e.Handled = true;

            }

        }

 

 

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *