我有一个WPF应用程序,其中包含一个用于显示调试文本输出的多行TextBox。
如何设置TextBox以便文本附加到框中,它会自动滚动到文本框的底部?
答案 0 :(得分:40)
@BojinLi提供的答案效果很好。 在阅读了@GazTheDestroyer链接的答案之后,我决定为TextBox实现我自己的版本,因为它看起来更干净。
总而言之,您可以使用附加属性扩展TextBox控件的行为。 (称为ScrollOnTextChanged)
使用它很简单:
<TextBox src:TextBoxBehaviour.ScrollOnTextChanged="True" VerticalScrollBarVisibility="Auto" />
这是TextBoxBehaviour类:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace MyNamespace
{
public class TextBoxBehaviour
{
static readonly Dictionary<TextBox, Capture> _associations = new Dictionary<TextBox, Capture>();
public static bool GetScrollOnTextChanged(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(ScrollOnTextChangedProperty);
}
public static void SetScrollOnTextChanged(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(ScrollOnTextChangedProperty, value);
}
public static readonly DependencyProperty ScrollOnTextChangedProperty =
DependencyProperty.RegisterAttached("ScrollOnTextChanged", typeof (bool), typeof (TextBoxBehaviour), new UIPropertyMetadata(false, OnScrollOnTextChanged));
static void OnScrollOnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var textBox = dependencyObject as TextBox;
if (textBox == null)
{
return;
}
bool oldValue = (bool) e.OldValue, newValue = (bool) e.NewValue;
if (newValue == oldValue)
{
return;
}
if (newValue)
{
textBox.Loaded += TextBoxLoaded;
textBox.Unloaded += TextBoxUnloaded;
}
else
{
textBox.Loaded -= TextBoxLoaded;
textBox.Unloaded -= TextBoxUnloaded;
if (_associations.ContainsKey(textBox))
{
_associations[textBox].Dispose();
}
}
}
static void TextBoxUnloaded(object sender, RoutedEventArgs routedEventArgs)
{
var textBox = (TextBox) sender;
_associations[textBox].Dispose();
textBox.Unloaded -= TextBoxUnloaded;
}
static void TextBoxLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var textBox = (TextBox) sender;
textBox.Loaded -= TextBoxLoaded;
_associations[textBox] = new Capture(textBox);
}
class Capture : IDisposable
{
private TextBox TextBox { get; set; }
public Capture(TextBox textBox)
{
TextBox = textBox;
TextBox.TextChanged += OnTextBoxOnTextChanged;
}
private void OnTextBoxOnTextChanged(object sender, TextChangedEventArgs args)
{
TextBox.ScrollToEnd();
}
public void Dispose()
{
TextBox.TextChanged -= OnTextBoxOnTextChanged;
}
}
}
}
答案 1 :(得分:9)
此解决方案的灵感来自Scott Ferguson's solution附加属性,但避免存储内部关联字典,因此代码更短:
using System;
using System.Windows;
using System.Windows.Controls;
namespace AttachedPropertyTest
{
public static class TextBoxUtilities
{
public static readonly DependencyProperty AlwaysScrollToEndProperty = DependencyProperty.RegisterAttached("AlwaysScrollToEnd",
typeof(bool),
typeof(TextBoxUtilities),
new PropertyMetadata(false, AlwaysScrollToEndChanged));
private static void AlwaysScrollToEndChanged(object sender, DependencyPropertyChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null) {
bool alwaysScrollToEnd = (e.NewValue != null) && (bool)e.NewValue;
if (alwaysScrollToEnd) {
tb.ScrollToEnd();
tb.TextChanged += TextChanged;
} else {
tb.TextChanged -= TextChanged;
}
} else {
throw new InvalidOperationException("The attached AlwaysScrollToEnd property can only be applied to TextBox instances.");
}
}
public static bool GetAlwaysScrollToEnd(TextBox textBox)
{
if (textBox == null) {
throw new ArgumentNullException("textBox");
}
return (bool)textBox.GetValue(AlwaysScrollToEndProperty);
}
public static void SetAlwaysScrollToEnd(TextBox textBox, bool alwaysScrollToEnd)
{
if (textBox == null) {
throw new ArgumentNullException("textBox");
}
textBox.SetValue(AlwaysScrollToEndProperty, alwaysScrollToEnd);
}
private static void TextChanged(object sender, TextChangedEventArgs e)
{
((TextBox)sender).ScrollToEnd();
}
}
}
据我所知,它的表现完全符合要求。这是一个测试用例,在一个窗口中有几个文本框,允许以各种方式设置附加的AlwaysScrollToEnd
属性(硬编码,带CheckBox.IsChecked
绑定和代码隐藏):
的Xaml:
<Window x:Class="AttachedPropertyTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AttachedPropertyTest" Height="800" Width="300"
xmlns:local="clr-namespace:AttachedPropertyTest">
<Window.Resources>
<Style x:Key="MultiLineTB" TargetType="TextBox">
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="Height" Value="60"/>
<Setter Property="Text" Value="{Binding Text, ElementName=tbMaster}"/>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox Background="LightYellow" Name="tbMaster" Height="150" AcceptsReturn="True"/>
<TextBox Style="{StaticResource MultiLineTB}" Grid.Row="1" local:TextBoxUtilities.AlwaysScrollToEnd="True"/>
<TextBox Style="{StaticResource MultiLineTB}" Grid.Row="2"/>
<TextBox Style="{StaticResource MultiLineTB}" Grid.Row="3" Name="tb3" local:TextBoxUtilities.AlwaysScrollToEnd="True"/>
<TextBox Style="{StaticResource MultiLineTB}" Grid.Row="4" Name="tb4"/>
<CheckBox Grid.Column="1" Grid.Row="4" IsChecked="{Binding (local:TextBoxUtilities.AlwaysScrollToEnd), Mode=TwoWay, ElementName=tb4}"/>
<Button Grid.Row="5" Click="Button_Click"/>
</Grid>
</Window>
代码隐藏:
using System;
using System.Windows;
using System.Windows.Controls;
namespace AttachedPropertyTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
void Button_Click(object sender, RoutedEventArgs e)
{
TextBoxUtilities.SetAlwaysScrollToEnd(tb3, true);
}
}
}
答案 2 :(得分:3)
嗯,这似乎是一个有趣的事情,所以我采取了一个裂缝。从一些眩目看来,似乎没有一种直接的方式来“告诉”文本框滚动到最后。所以我想到了另一种方式。 WPF中的所有框架控件都有一个默认的Style / ControlTemplate,并且根据Textbox控件的外观判断,必须有一个处理滚动的ScrollViewer。因此,为什么不使用默认Textbox ControlTemplate的本地副本并以编程方式获取ScrollViewer。然后,我可以告诉ScrollViewer将其内容滚动到最后。事实证明这个想法很有效。
这是我写的测试程序,可以使用一些重构,但你可以通过查看它来获得想法:
这是XAML:
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication3="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<!--The default Style for the Framework Textbox-->
<SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" />
<SolidColorBrush x:Key="DisabledBackgroundBrush" Color="#EEE" />
<SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFF" />
<SolidColorBrush x:Key="SolidBorderBrush" Color="#888" />
<ControlTemplate x:Key="MyTextBoxTemplate" TargetType="{x:Type TextBoxBase}">
<Border x:Name="Border" CornerRadius="2" Padding="2" Background="{StaticResource WindowBackgroundBrush}"
BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1">
<ScrollViewer Margin="0" x:Name="PART_ContentHost" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" />
<Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBackgroundBrush}" />
<Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="MyTextBox" TargetType="{x:Type TextBoxBase}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="KeyboardNavigation.TabNavigation" Value="None" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="MinWidth" Value="120" />
<Setter Property="MinHeight" Value="20" />
<Setter Property="AllowDrop" Value="true" />
<Setter Property="Template" Value="{StaticResource MyTextBoxTemplate}"></Setter>
</Style>
</Window.Resources>
<Grid>
<WpfApplication3:AutoScrollTextBox x:Name="textbox" TextWrapping="Wrap" Style="{StaticResource MyTextBox}"
VerticalScrollBarVisibility="Visible" AcceptsReturn="True" Width="100" Height="100">test</WpfApplication3:AutoScrollTextBox>
</Grid>
</Window>
背后的代码:
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
textbox.AppendText("Line " + i + Environment.NewLine);
}
}
}
public class AutoScrollTextBox : TextBox
{
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
// Make sure the Template is in the Visual Tree:
// http://stackoverflow.com/questions/2285491/wpf-findname-returns-null-when-it-should-not
ApplyTemplate();
var template = (ControlTemplate) FindResource("MyTextBoxTemplate");
var scrollViewer = template.FindName("PART_ContentHost", this) as ScrollViewer;
//SelectionStart = Text.Length;
scrollViewer.ScrollToEnd();
}
}
}
答案 3 :(得分:3)
更便携的方式可能是使用附加属性,例如this similar question for listbox。
(只需在VerticalOffset
属性更改时设置Text
)
答案 4 :(得分:3)
其他答案的类似答案,但没有静态事件和控制字典。 (恕我直言,如果可能的话,最好避免静态事件。)
public class ScrollToEndBehavior
{
public static readonly DependencyProperty OnTextChangedProperty =
DependencyProperty.RegisterAttached(
"OnTextChanged",
typeof(bool),
typeof(ScrollToEndBehavior),
new UIPropertyMetadata(false, OnTextChanged)
);
public static bool GetOnTextChanged(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(OnTextChangedProperty);
}
public static void SetOnTextChanged(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(OnTextChangedProperty, value);
}
private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var textBox = dependencyObject as TextBox;
var newValue = (bool)e.NewValue;
if (textBox == null || (bool)e.OldValue == newValue)
{
return;
}
TextChangedEventHandler handler = (object sender, TextChangedEventArgs args) =>
((TextBox)sender).ScrollToEnd();
if (newValue)
{
textBox.TextChanged += handler;
}
else
{
textBox.TextChanged -= handler;
}
}
}
这只是其他发布的解决方案的替代方案,这是我在寻找一段时间后找到的最好的解决方案(即简洁和mvvm)。
答案 5 :(得分:1)
“ScrollToEnd”方法的问题是TextBox必须可见,否则它不会滚动。
因此,更好的方法是将TextBox Selection属性设置为文档的结尾:
static void tb_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == null)
{
return;
}
// set selection to end of document
tb.SelectionStart = int.MaxValue;
tb.SelectionLength = 0;
}
顺便说一下,第一个例子中的内存泄漏处理是likely unnecessary。 TextBox是发布者,静态附加属性事件处理程序是订阅者。发布者保留对订阅者的引用,这可以使订阅者保持活跃(而不是反过来。)因此,如果TextBox超出范围,那么对静态事件处理程序的引用也将如此(即,没有内存泄漏。)
因此,可以更简单地处理附属财产:
static void OnAutoTextScrollChanged
(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
TextBox tb = obj as TextBox;
if (tb == null)
{
return;
}
bool b = (bool)args.NewValue;
if (b)
{
tb.TextChanged += tb_TextChanged;
}
else
{
tb.TextChanged -= tb_TextChanged;
}
}