簡體   English   中英

ScrollToAsync .Net Maui 僅在我第二次按下按鈕時有效

[英]ScrollToAsync .Net Maui only Works the second time I press the button

我目前正在開發一個聊天程序,當我顯示兩個人的聊天歷史記錄時,我想滾動到垂直堆棧布局的最后一條消息/結尾 --> 我使用 .ScrollToAsync 函數來完成。

如果我單擊其中一個用戶按鈕,則會從本地存儲方法加載歷史記錄。 之后,程序為每條消息創建一個標簽,並將其添加到可滾動的垂直堆棧布局中。 之后,它應該滾動到垂直堆棧布局的末尾。 使用以下代碼片段:

await Scroller.ScrollToAsync(TextField, ScrollToPosition.End, false);  

完整的方法在這里:

private async void OnCounterClicked(object sender, EventArgs e)
    {
        if (m_currentLabels != null)
        {
            foreach(Label label in m_currentLabels)
            {
                TextField.Remove(label);
            }
        }

        m_currentLabels = new List<Label>();
        Button button =(Button) sender;
        string str = button.Text;
        Guid userId = m_userDictionary[str];
        List<Guid> guids = new List<Guid>();
        guids.Add(userId);
        m_currChannelPartners = guids;

        List<MessageModel> localMessages = m_eChatBusiness.GetMessages(MessageModel.Yourself.ID, guids);
        foreach(MessageModel message in localMessages)
        {
            Label messageLabel = new Label();
            messageLabel.Text = $"{message.Created} {message.Message} | {GetStatus(message)}";
            messageLabel.TextColor = Color.Parse("White");
            messageLabel.HorizontalTextAlignment = message.Position == "End"? TextAlignment.End:TextAlignment.Start;
            m_currentLabels.Add(messageLabel);
            TextField.Add(messageLabel);
        }

        await Scroller.ScrollToAsync(TextField, ScrollToPosition.End, false); 
    }

Scroller 是 ScrollView,TextField 是垂直堆棧布局。

奇怪的是:當我第二次單擊該按鈕時,它起作用了。 我試圖猜測,但是由於我在方法的末尾調用了異步函數,所以 TextField 應該完全初始化還是沒有?

我希望你能幫幫我!

在我的主管的幫助下,我找到了解決該問題的方法:

您必須啟用一個計時器對象,該對象獲取一個函數,該函數在 mainThread 內調用所需的函數 Scroller.ScrollToAsync(TextField, ScrollToPosition.End, false) (否則會引發異常)。 重要的是無限超時,以便操作只執行一次。

這是代碼,如果有人有同樣的問題:

Timer timer = new Timer((object obj) => {
            MainThread.BeginInvokeOnMainThread(() => Scroller.ScrollToAsync(TextField, ScrollToPosition.End, false));
        }, null, 100, Timeout.Infinite);

100 是計時器對象在執行前等待的時間。 現在真正的好處是,用戶界面不再被阻塞!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM