views:

39

answers:

1

I have seen this question:

http://stackoverflow.com/questions/642498/how-to-keep-wpf-textbox-selection-when-not-focused

And have implemented the solution there, so that my textbox shows the selection, even when it does not have focus.

However, when I change the selection start or length, nothing changes visually in the textbox. Also, when I scroll the textbox programatically and it does not have focus, the selection brush does not move with the text as it scrolls.

+1  A: 

If you define a separate focus scope in XAML to maintain the selection (see StackPanel below) and you set the focus in the TextBox once (in this case when the Window opens using FocusManager.FocusedElement) then you should see your selection change programatically.

Here is some sample code to get you started:

<Window x:Class="RichTextFont2.Views.MainView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Main Window" 
  Height="400" Width="400" 
  FocusManager.FocusedElement="{Binding ElementName=myTextBox}"
  FontSize="20">

  <DockPanel>
    <Grid>
      <Grid.RowDefinitions>
          <RowDefinition Height="60"/>
          <RowDefinition/>
      </Grid.RowDefinitions>
      <TextBox x:Name="myTextBox" 
               Grid.Row="0" 
               Text="Text that does not loose selection." 
               TextWrapping="Wrap" 
               VerticalScrollBarVisibility="Auto">
      </TextBox>
      <StackPanel Grid.Row="1" FocusManager.IsFocusScope="True">
        <Button Content="Select Text" Click="Button_Click_MoveTextBox"/>
      </StackPanel>
    </Grid>
  </DockPanel>
</Window>

Here is some code to handle the button click event:

private void Button_Click_MoveTextBox(object sender, RoutedEventArgs e)
{
   if (myTextBox.SelectionStart >= myTextBox.Text.Length)
   {
      myTextBox.SelectionStart = 0;
   }
   else
   {
      myTextBox.SelectionStart += 9;
   }
   myTextBox.SelectionLength = 6;
   myTextBox.LineDown();
}
Zamboni
Thank-you, the IsFocusScope solution seems much more elegant, than the solution presented in the question I linked to. In order to change the selection programatically, I still need to temporarily focus the textbox.
Justin