xamarin UWP设置HUD加载功能

时间:2023-03-08 22:32:44
xamarin UWP设置HUD加载功能

使用xamarin开发的时候经常用到加载HUD功能,就是我们常见的一个加载中的动作,Android 下使用 AndHUD , iOS 下使用 BTProgressHUD, 这两个在在 NuGet 上都有。在UWP中本身提供的方式,并不能完全满足我们的需求,因此我们需要使用Dependencies来重新定义平台的HUD功能,这时可以使用Popup来完成。popup本身是一个弹窗控件,可以在控件中添加各种其他的控件,这为我们自定义弹窗带来了方便。首先我们要把popup设置大小为应用App所见区域的大小。再在Popup的中间加载一个Grid,Grid里面加载所需多文字和图片就可以来。实例代码如下:

using BS.Dependencies;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
using Windows.UI;
using Windows.UI.Xaml; [assembly: Dependency(typeof(BS.UWP.Dependencies.HUDUWP))]
namespace BS.UWP.Dependencies
{
public class HUDUWP : IHUD
{
private Windows.UI.Xaml.Controls.Grid Container = new Windows.UI.Xaml.Controls.Grid() {
Background = new SolidColorBrush(Colors.Black),
CornerRadius = new CornerRadius(),
Padding = new Windows.UI.Xaml.Thickness(),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
}; private Popup Popup = null; public HUDUWP()
{
this.Popup = new Popup()
{
Child = new Border()
{
Width = Window.Current.Bounds.Width,
Height = Window.Current.Bounds.Height,
Background = new SolidColorBrush(Colors.Gray),
Opacity = 0.6,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Child = this.Container,
}
};
} public void Show()
{
this.Show("Hello World", );
} public void Show(string message)
{
this.Show(message, );
}
public void Show(string message, int delay = )
{
this.Popup.IsOpen = true;
this.Container.Children.Clear(); this.Container.Children.Add(new TextBlock()
{
Text = message,
Foreground = new SolidColorBrush(Colors.White),
FontSize =
});

Task.Delay(delay)
                .ContinueWith(t =>
                  {
                     Device.BeginInvokeOnMainThread(() =>
                      {
                         this.Popup.IsOpen = false;
                      });
                  }
             );

        }

        public void Dismiss()
{
this.Popup.IsOpen = false;
}
}
}

已上代码经本人测试可以使用,希望对你开发有用。同时修改下上面代码在win8.1和winPhone平台下都可以使用。如有更好的方法请留言。