CPF/CPF.Toolkit/ViewModelBase.cs

51 lines
2.0 KiB
C#
Raw Normal View History

using CPF.Controls;
using CPF.Toolkit.Dialogs;
2023-11-22 17:30:26 +08:00
using System;
using System.Collections.Generic;
using System.Text;
2023-11-22 23:55:50 +08:00
using System.Threading.Tasks;
2023-11-22 17:30:26 +08:00
namespace CPF.Toolkit
{
2023-11-22 23:55:50 +08:00
public class ViewModelBase : ObservableObject, IClosable, IDialog, ILoading
2023-11-22 17:30:26 +08:00
{
2023-11-29 17:07:17 +08:00
event EventHandler<ClosingEventArgs> _close;
2023-11-22 23:55:50 +08:00
event Func<string, Task, Task<object>> _showLoadingFunc;
event Func<string, Task, Task> _showLading;
2023-11-29 17:07:17 +08:00
event EventHandler<ClosingEventArgs> IClosable.Closable { add => this._close += value; remove => this._close -= value; }
2023-11-22 23:55:50 +08:00
event Func<string, Task, Task<object>> ILoading.ShowLoadingFunc { add => this._showLoadingFunc += value; remove => this._showLoadingFunc -= value; }
event Func<string, Task, Task> ILoading.ShowLoading { add => this._showLading += value; remove => this._showLading -= value; }
2023-11-22 23:55:50 +08:00
void IClosable.OnClosable(object sender, ClosingEventArgs e) => this.OnClose(e);
2023-11-22 23:55:50 +08:00
public IDialogService Dialog { get; set; }
2023-11-29 17:07:17 +08:00
protected void Close()
{
2023-11-23 09:57:32 +08:00
if (this._close == null) throw new ArgumentNullException();
2023-11-29 17:07:17 +08:00
this._close.Invoke(this, new ClosingEventArgs());
}
protected virtual void OnClose(ClosingEventArgs e) { }
2023-11-22 23:55:50 +08:00
protected async Task ShowLoading(Task task)
{
if (this._showLading == null) throw new ArgumentNullException();
await this._showLading.Invoke("加载中……", task);
}
2023-11-23 09:57:32 +08:00
protected async Task ShowLoading(Func<Task> task)
{
if (this._showLoadingFunc == null) throw new ArgumentNullException();
await this._showLading.Invoke("加载中……", task.Invoke());
}
2023-11-22 23:55:50 +08:00
protected async Task<T> ShowLoading<T>(Func<Task<T>> task)
{
if (this._showLoadingFunc == null) throw new ArgumentNullException();
var result = await this._showLoadingFunc.Invoke("加载中……", task.Invoke());
return (T)result;
}
2023-11-22 17:30:26 +08:00
}
}