zl程序教程

您现在的位置是:首页 >  后端

当前栏目

.NET MAUI实战 Dispatcher

Net 实战 MAUI Dispatcher
2023-06-13 09:15:42 时间

详细内容

这一期分享的内容非常简单,在之前使用过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...
            });

            //延迟1s
            Shell.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");
        }
    }
}