詳細內容
這一期分享的內容非常簡單,在之前使用過WPF的開發者對MVVM開發模式下ViewModel中后臺線程轉UI線程并不陌生使用Appplication.Current.Dispatcher。那么在.NET MAUI中也有同樣的機制,存在于.NET MAUI Shell對象中。
那么什么是Shell?
官網描述如下,.NET 多平臺應用 UI (.NET MAUI) Shell 通過提供大多數應用所需的基本功能(包括:
用于描述應用的視覺層次結構的單個位置。
常見的導航用戶體驗。
基于 URI 的導航方案,允許導航到應用中的任何頁面。
集成的搜索處理程序。
其他內容就不搬運了,大伙可以參考下面鏈接內容。
ref:https://docs.microsoft.com/zh-cn/dotnet/maui/fundamentals/shell/
接下來我們直接來看看實際運用是如何的,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace MauiApp1.ViewModels
{public class MainViewModel{public void Do() {//同步Shell.Current.Dispatcher.Dispatch(() =>{//code...});//異步非阻塞Shell.Current.Dispatcher.DispatchAsync(() => {//code...});//延遲1sShell.Current.Dispatcher.DispatchDelayed(new TimeSpan(1000), () =>{//code...});}}
}
如果在MVVM開發模式下,還想在ViewModel中彈出消息框,那么同樣也可以在Shell中訪問。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace MauiApp1.ViewModels
{public class MainViewModel{public void Do() {Shell.Current.DisplayAlert("message title","message content","cancel");}}
}