Skip to content

Commit 4458c5b

Browse files
committed
feat: 优化滚动体验. 现在接收消息的时候不会锁定滚动了
1 parent 8040ced commit 4458c5b

2 files changed

Lines changed: 49 additions & 2 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
using System.Windows.Controls;
7+
8+
namespace OpenGptChat.Utilities
9+
{
10+
static class ScrollViewerUtils
11+
{
12+
public static bool IsAtEnd(this ScrollViewer scrollViewer, int threshold = 5)
13+
{
14+
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
15+
return true;
16+
17+
if (scrollViewer.VerticalOffset + threshold >= scrollViewer.ScrollableHeight)
18+
return true;
19+
20+
return false;
21+
}
22+
}
23+
}

OpenGptChat/Views/Pages/ChatPage.xaml.cs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
using System;
1+
 using System;
22
using System.Threading.Tasks;
33
using System.Windows;
44
using System.Windows.Controls;
5+
using System.Windows.Input;
56
using CommunityToolkit.Mvvm.Input;
67
using OpenGptChat.Models;
78
using OpenGptChat.Services;
9+
using OpenGptChat.Utilities;
810
using OpenGptChat.ViewModels;
911

1012
namespace OpenGptChat.Views.Pages
@@ -31,6 +33,8 @@ public ChatPage(
3133

3234
InitializeComponent();
3335

36+
messageScrollViewer.PreviewMouseWheel += CloseAutoScrollWhileMouseWheel;
37+
messageScrollViewer.ScrollChanged += EnableAutoScrollWhileAtEnd;
3438
smoothScrollingService.Register(messageScrollViewer);
3539
}
3640

@@ -42,6 +46,7 @@ public ChatPage(
4246

4347
public Guid SessionId { get; private set; }
4448

49+
4550
public void InitSession(Guid sessionId)
4651
{
4752
SessionId = sessionId;
@@ -70,6 +75,10 @@ public async Task SendAsync()
7075
}
7176

7277

78+
// 发个消息, 将自动滚动打开, 如果已经在底部, 则将自动滚动打开
79+
if (messageScrollViewer.IsAtEnd())
80+
autoScrollToEnd = true;
81+
7382

7483
string input = ViewModel.InputBoxText.Trim();
7584
ViewModel.InputBoxText = string.Empty;
@@ -117,10 +126,25 @@ public void Copy(string text)
117126
Clipboard.SetText(text);
118127
}
119128

129+
130+
131+
bool autoScrollToEnd = false;
132+
133+
private void CloseAutoScrollWhileMouseWheel(object sender, MouseWheelEventArgs e)
134+
{
135+
autoScrollToEnd = false;
136+
}
137+
138+
private void EnableAutoScrollWhileAtEnd(object sender, ScrollChangedEventArgs e)
139+
{
140+
if (messageScrollViewer.IsAtEnd())
141+
autoScrollToEnd = true;
142+
}
143+
120144
[RelayCommand]
121145
public void ScrollToEndWhileReceiving()
122146
{
123-
if (SendCommand.IsRunning)
147+
if (SendCommand.IsRunning && autoScrollToEnd)
124148
messageScrollViewer.ScrollToEnd();
125149
}
126150
}

0 commit comments

Comments
 (0)