.NET MAUI实战 Dispatcher

详细内容

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

366862196b81dddfad8c385632db6c81.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值