2010-08-18 75 views

回答

1

如果您在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(); 
} 
+1

感谢信中,IsFocusScope解决方案似乎更优雅,而不是问题I中提出的解决方案。为了以编程方式更改选择,我仍然需要暂时关注文本框。 – Justin 2010-08-22 05:49:12

相关问题