-1

How to highlight text in Wpf when Text box is not focused? (.NET 4.0)

Khmel
  • 11
  • 1

2 Answers2

0

If you handle the LostFocus event of your TextBox, you can use the following code to select the contents of the TextBox:

textBox.SelectAll();
e.Handled = true;
thesheps
  • 635
  • 4
  • 11
  • That doesn't work, when window is inactive, selected text is not highlighted. **I can override OnLostKeyboardFocus, but it's bung!!** – Khmel Mar 21 '13 at 10:44
  • Going back to my original comment, then, what *have* you tried so far? Providing answers which equate to steps you've already tried is time-wasting for us both! – thesheps Mar 21 '13 at 11:07
  • Without these comments turning into a one-on-one discussion, you have still not provided us with any code examples of what you've attempted so far. Nor do we have any context for your problem for us to be able to suggest any useful solution. – thesheps Mar 21 '13 at 11:16
  • I want to do a search dialogue [such as in notepad++](http://dl.dropbox.com/u/20573569/Jpg/Untitled.jpg) – Khmel Mar 21 '13 at 11:28
0

You can use a Style with a EventTrigger for the TextBox.LostFocus/GotFoxus events.

This will change the TextBox Foreground to Red with a 1sec delay when "LostFocus" is "true"

 <Style x:Key="tboxStandard"
     TargetType="{x:Type TextBox}">
<Setter Property="BorderThickness"
        Value="2" />
<Setter Property="BorderBrush"
        Value="#292929" />
<Setter Property="Background"
        Value="#E9E9E9" />
<Setter Property="TextAlignment"
        Value="Center" />
<Setter Property="Foreground"
        Value="#191919" />
<Style.Triggers>
  <EventTrigger RoutedEvent="TextBox.GotFocus">
    <EventTrigger.Actions>
      <BeginStoryboard>
        <Storyboard>
          <ColorAnimation Storyboard.TargetProperty="(TextBox.Foreground).(SolidColorBrush.Color)"
                          To="#191919"
                          Duration="0:0:1" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger.Actions>
  </EventTrigger>
  <EventTrigger RoutedEvent="TextBox.LostFocus">
    <EventTrigger.Actions>
      <BeginStoryboard>
        <Storyboard>
          <ColorAnimation Storyboard.TargetProperty="(TextBox.Foreground).(SolidColorBrush.Color)"
                          To="Red"
                          Duration="0:0:1" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger.Actions>
  </EventTrigger>
</Style.Triggers>

hijack
  • 263
  • 2
  • 3
  • 11
  • Thanks for Your answer, but I didn't want change color of all text, I want highlight only selected text. – Khmel Mar 21 '13 at 18:52
  • In my Style I provided there is a "TextBox.GotFocus" this will run only if you have selected/got focus of the text. This should work for you, otherwise I don't understand what you want to accomplish. – hijack Mar 22 '13 at 08:30
  • I hope [this picture](https://dl.dropbox.com/u/20573569/Jpg/Untitled.jpg) help you understand this issue – Khmel Mar 22 '13 at 18:34