C# 使用数据绑定时如何自动滚动AvaloniUI ScrollViewer?
我的AvaloniaUI应用程序中有以下设置:C# 使用数据绑定时如何自动滚动AvaloniUI ScrollViewer?,c#,.net-core,avaloniaui,C#,.net Core,Avaloniaui,我的AvaloniaUI应用程序中有以下设置: <ScrollViewer VerticalScrollBarVisibility="Auto" AllowAutoHide="True" Name="MessageLogScrollViewer"> <TextBlock HorizontalAlignment="Stretch"
<ScrollViewer VerticalScrollBarVisibility="Auto"
AllowAutoHide="True"
Name="MessageLogScrollViewer">
<TextBlock HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
TextWrapping="NoWrap"
Text="{Binding ReceivedMessages}"></TextBlock>
</ScrollViewer>
然后,我尝试从我的ViewModel调用该函数:
private string receivedMessages = string.Empty;
public string ReceivedMessages
{
get => receivedMessages;
set => this.RaiseAndSetIfChanged(ref receivedMessages, value);
}
...
private MainWindow _window;
public MainWindowViewModel(MainWindow window)
{
_window = window;
}
...
ReceivedMessage += "\n";
ReceivedMessages += ReceivedMessage;
_window.ScrollTextToEnd(); // Does not work.
但不幸的是,这需要从UI线程调用ScrollToEnd()
函数,因为我遇到了一个异常:
System.InvalidOperationException:“来自无效线程的调用”
我的问题是,每当我通过数据绑定更新TextBlocks Text属性时,如何将ScrollViewer自动滚动到最后?好的,我已经找到了答案,但将其保留在这里供参考 为了从UI线程上的另一个线程执行函数,需要调用
Dispatcher.UIThread.InvokeAsync(_window.ScrollTextToEnd);
但是这只滚动到倒数第二行,所以当我调用ScrollTextToEnd()
时,控件似乎还没有更新。因此,我在更新文本和像这样调用滚动函数之间添加了一个短超时
ReceivedMessages += ReceivedMessage;
// A short timeout is needed, so that the scroll viewer will scroll to the new end of its content.
Thread.Sleep(10);
Dispatcher.UIThread.InvokeAsync(_window.ScrollTextToEnd);
它现在就是这样工作的
ReceivedMessages += ReceivedMessage;
// A short timeout is needed, so that the scroll viewer will scroll to the new end of its content.
Thread.Sleep(10);
Dispatcher.UIThread.InvokeAsync(_window.ScrollTextToEnd);