在 WPF 中自动滚动到文本块的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18003960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto scroll to the end of a Textblock in WPF
提问by Daybreaker
I want to view the content of a textblock that was added last. It means I want to auto scroll to the end and view the hidden content when I add more text... just like in Windows calculator.
我想查看最后添加的文本块的内容。这意味着当我添加更多文本时,我想自动滚动到最后并查看隐藏的内容......就像在 Windows 计算器中一样。
In the calculator when I enter more numbers it shows only the numbers entered last. Previously entered numbers are hidden when there is not enough space. I want to do the exact same thing..
在计算器中,当我输入更多数字时,它只显示最后输入的数字。当没有足够的空间时,先前输入的数字将被隐藏。我想做同样的事情..
Can someone please help me?
有人可以帮帮我吗?
回答by Steve
I don't think TextBlocks can scroll. You can put the TextBlockin a ScrollViewer.
我不认为TextBlocks 可以滚动。你可以把TextBlock一个ScrollViewer。
XAML:
XAML:
<ScrollViewer Name="MyScrollViewer">
<TextBlock TextWrapping="Wrap">
A bunch of text
</TextBlock>
</ScrollViewer>
Code-behind:
代码隐藏:
MyScrollViewer.ScrollToBottom();
It appears that if you have multiple TextBlocks in a ListBox, you cannot get access very easily to it's ScrollViewer to accomplish the same thing. If you are doing this, change your ListBox to an ItemsControl and put that into a ScrollViewer. I think you'll lose selection ability though.
看起来,如果您在 ListBox 中有多个 TextBlock,则无法很容易地访问它的 ScrollViewer 来完成相同的事情。如果您这样做,请将您的 ListBox 更改为 ItemsControl 并将其放入 ScrollViewer。我认为你会失去选择能力。
If you do need to use a ListBox, then you can get the view that belongs to the last item and call the ListBox's ScrollIntoView() method. See thisor thisfor a little bit about that, but you might have to do a little more research.
如果确实需要使用 ListBox,则可以获取属于最后一项的视图并调用 ListBox 的 ScrollIntoView() 方法。请参阅this或this了解一点,但您可能需要做更多的研究。
回答by Sean Beanland
Do you mean a TextBox, as opposed to a TextBlock? The default behavior for a TextBox is to show the most recent text as more text is entered.
你的意思是文本框,而不是文本块?TextBox 的默认行为是在输入更多文本时显示最近的文本。
Window x:Class="textboxscrolltest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Width="75" Height="25"/>
</Grid>
</Window>

