开发者

How can I change the selection in an unfocused textbox?

I have seen this question:

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 programati开发者_如何学Pythoncally and it does not have focus, the selection brush does not move with the text as it scrolls.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜