2010-05-10 40 views
1

我想在我的WPF應用程序 中simmulate控制檯文本輸出,但是當我在TextBox中添加新行時,我應該使用滾動條來查看最後添加的文本,但是我希望看到最後添加的文本,但對於首創線使用滾動條WPF如何查看TexBox中最後添加的文本行

<TextBox TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" 
        Text="{Binding Path=Data, Mode=TwoWay}" />` 

回答

1

使用文本框的ScrollToLine方法(和LineCount財產知道有多少行有)爲了添加文字後以確保剛剛添加的行可見。

1

請考慮直接從代碼滾動文本框的背後是這樣的(例如,當文本的變化):

private void SampleTextBox_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    if (SampleTextBox.LineCount != -1) 
    { 
     SampleTextBox.ScrollToLine(SampleTextBox.LineCount - 1); 
    } 
} 

請告訴我,如果這有助於。

0

感謝回答:我預計從XAML做,但我undestood它只能從後面的代碼 所以這裏是我的執行力度現在複選框停止ScrollToEnd功能:

public partial class MainWindow : Window 
{ 
    private bool isScrollToEnd; 
    Timer timer; 

    public double WaitTime 
    { 
     get { return waitTime/1000; } 
     set { waitTime = value * 1000; } 
    } 
    private double waitTime; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     isScrollToEnd = true; 
     waitTime = 5000; 
     tbWaitTime.DataContext = this; 
     timer = new Timer(waitTime); 
     timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
    } 

    // событие изменения текста в контроле tbConsole 
    private void tbConsole_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (tbConsole.LineCount != -1 && isScrollToEnd) 
     { 
      tbConsole.ScrollToLine(tbConsole.LineCount - 1); 
      cbIsScrolling.IsChecked = false; 
     } 
    } 

    private void cbIsScrolling_Click(object sender, RoutedEventArgs e) 
    { 
     if ((bool)cbIsScrolling.IsChecked) 
     { 
      isScrollToEnd = !(bool)cbIsScrolling.IsChecked; 
      isScrollToEnd = false; 
      timer.Interval = waitTime; 
      timer.Start(); 
      return; 
     } 
     isScrollToEnd = true; 
     timer.Stop(); 
     cbIsScrolling.IsChecked = false; 
    } 

    void timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     timer.Stop(); 
     isScrollToEnd = true; 
    } 
} 

,這裏是XAML代碼:

<StackPanel Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Grid.RowSpan="2"> 
     <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,3,10,2" VerticalAlignment="Top"> 
      <Label Content="Stop autoscrolling for:" /> 
      <TextBox Name="tbWaitTime" Text="{Binding Path=WaitTime}" 
        MinWidth="25" MaxWidth="50" Margin="5,0,0,0" /> 
      <Label Content="sec."/> 
      <CheckBox Name="cbIsScrolling" 
         HorizontalAlignment="Right" VerticalAlignment="Center" 
         Click="cbIsScrolling_Click" /> 
     </StackPanel> 
     <TextBox Name="tbConsole" 
        Background="LightGoldenrodYellow" Padding="5" Height="100" 
        VerticalScrollBarVisibility="Auto" 
        TextWrapping="Wrap" 
        AcceptsReturn="True" 
        Text="{Binding Path=Data, Mode=TwoWay}" TextChanged="tbConsole_TextChanged" /> 
    </StackPanel> 
相關問題