繁体   English   中英

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

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

我已经看到了这个问题:

不关注时如何保持WPF TextBox选择?

并在那里实施了解决方案,因此即使没有焦点,我的文本框也可以显示选择。

但是,当我更改选择起点或长度时,文本框中的外观没有任何变化。 另外,当我以编程方式滚动文本框并且没有焦点时,选择画笔不会随着文本滚动而移动。

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

以下是一些示例代码,可帮助您入门:

<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>

这是一些处理按钮单击事件的代码:

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