субота, 13 червня 2009 р.

Correct way to keep selection in TextBox and RichTextBox visible after focus lost in WPF

WPF controls: TextBox and RichTextBox have no HideSelection property. Due to this, it is a bit tricky to make them to show selection after focus lost.

There are two possible solutions.

1. Defining separate focus scope in XAML
2. Adding and event handler (LostFocus) and set Handled property of RoutedEventArgs to true in code.

As the second one seems to be tricky, I will show how to implement this behavior with the first concept:

<Window
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<StackPanel>
<TextBox Margin="5">Some text here</TextBox>

<StackPanel Grid.Row="1" FocusManager.IsFocusScope="True">
  <ComboBox Margin="5">
  <ComboBoxItem IsSelected="True">123</ComboBoxItem>
  <ComboBoxItem>123</ComboBoxItem>
  </ComboBox>
</StackPanel>
</StackPanel>

</Window>

This code will create window with two controls (TextBox and ComboBox):

As you can see, both controls can have focus simultaneously. This happens because of the FocusManager.IsFocusScope property set to true which makes second control to be in a separate focus scope.

However, if new window is opened, focus on both controls will be lost.

You can read more about focus management in WPF here:
http://msdn.microsoft.com/en-us/library/aa969768.aspx