带有绑定文本的WPF文本块不会滚动

时间:2016-05-23 19:12:44

标签: c# wpf xaml mvvm

我的TextBlock中的文本绑定到我的代码中的元素。但是,当我第一次打开窗口时,Textblock完全是空的。当我添加文本时,我需要ScrollViewer允许我向下滚动文本,或者在添加更多文本时自动向下滚动。使用MVVM,所以没有任何代码可以理想。

<StackPanel Grid.Column="0" Grid.Row="1" Margin="0 10">
    <Label Style="{StaticResource LabelStyle}">Output</Label>
    <ScrollViewer VerticalScrollBarVisibility="Visible" Height="100">
        <TextBlock ScrollViewer.CanContentScroll="True" Height="100" VerticalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding Path=ProcessingOutput}"/>
    </ScrollViewer>
</StackPanel>

我怎样才能实现这一目标?有没有办法更新ScrollViewer,以便它看到更多文本超出我在TextBlock中看到的内容并允许用户向下滚动,或允许我设置自动滚动功能,当通过绑定添加文本时自动向下滚动?

提前致谢!

1 个答案:

答案 0 :(得分:1)

如果您从Height="100"

中删除TextBlock

滚动条将会有效

使其在文本更改时滚动其他答案建议使用ScrollViwer.ScrollToBottom()方法,例如像这样:

<ScrollViewer Name="scroll"
              VerticalScrollBarVisibility="Visible" 
              Height="100">
    <TextBlock ScrollViewer.CanContentScroll="True" 
               VerticalAlignment="Stretch" 
               TextWrapping="Wrap" 
               Text="{Binding Path=ProcessingOutput, NotifyOnTargetUpdated=True}"
               TargetUpdated="Txt_OnTargetUpdated">
        </TextBlock>
</ScrollViewer>
private void Txt_OnTargetUpdated(object sender, DataTransferEventArgs e)
{
    scroll.ScrollToBottom();
}
相关问题