简体   繁体   English

如何在未聚焦的文本框中更改选择?

[英]How can I change the selection in an unfocused textbox?

I have seen this question: 我已经看到了这个问题:

How to keep WPF TextBox selection when not focused? 不关注时如何保持WPF TextBox选择?

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. 另外,当我以编程方式滚动文本框并且没有焦点时,选择画笔不会随着文本滚动而移动。

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. 如果您在XAML中定义了一个单独的焦点范围以维护选择(请参见下面的StackPanel),并且一次在TextBox中设置了焦点(在这种情况下,当窗口使用FocusManager.FocusedElement打开时),那么您应该以编程方式看到选择的变化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM