增加全局账户名同步
增加静态变量
添加文件:Mytodo.Common.Models.AppSession.cs
ausing Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace Mytodo.Common.Models
{
public class AppSession
{
private static String userName;
/// <summary>
/// A static property which you'd like to bind to
/// </summary>
public static String UserName
{
get
{
return userName;
}
set
{
userName = value;
// Raise a change event
OnUserNameChanged(EventArgs.Empty);
}
}
// Declare a static event representing changes to your static property
public static event EventHandler UserNameChanged;
// Raise the change event through this static method
protected static void OnUserNameChanged(EventArgs e)
{
EventHandler handler = UserNameChanged;
if (handler != null)
{
handler(null, e);
}
}
static AppSession()
{
// Set up an empty event handler
UserNameChanged += (sender, e) => { return; };
}
}
}
修改MainView绑定
- 增加命名空间
xmlns:model="clr-namespace:Mytodo.Common.Models"
- 修改textblock绑定
<TextBlock
Margin="0,10"
HorizontalAlignment="Center"
Text="{Binding Path=(model:AppSession.UserName)}" />
给账户名赋值
修改Mytodo.ViewModels.LoginViewModel.cs
async private void Login()
{
if (string.IsNullOrWhiteSpace(Account) ||
string.IsNullOrWhiteSpace(Password))
{
aggregator.SendMessage("密码或账户为空,请重新输入", "Login");
return;
}
var loginResult = await loginService.Login(new UserDto()
{
Account = Account,
PassWord = Password
});
if (loginResult != null && loginResult.Status)
{
//UserDto myuser= new UserDto() { UserName=loginResult.Result }
// AppSession.UserName
AppSession.UserName = (loginResult.Result as UserDto).UserName;
RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
return;
}
else
{
//登录失败提示...
aggregator.SendMessage("密码或账户错误,请重新输入", "Login");
}
}
添加注销功能
添加注销方法
修改文件:Mytodo.app.xaml.cs
public static void LoginOut(IContainerProvider containerProvider)
{
Current.MainWindow.Hide();
var dialog = containerProvider.Resolve<IDialogService>();
dialog.ShowDialog("LoginView", callback =>
{
if (callback.Result != ButtonResult.OK)
{
Environment.Exit(0);
return;
}
Current.MainWindow.Show();
});
}
添加注销命令,并初始化
修改文件:Mytodo.ViewModels.MainViewModel.cs
using Mytodo.Common;
using Mytodo.Common.Models;
using Mytodo.Extensions;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Mytodo.ViewModels
{
public class MainViewModel : BindableBase, IConfigureInterface
{
public MainViewModel(IRegionManager regm, IContainerProvider provider)
{
MenuBars = new ObservableCollection<MenuBar>();
//区域赋值
this.regionManager = regm;
this.provider = provider;
//初始化命令操作
NavigateCmd = new DelegateCommand<MenuBar>(Navigate);
LoginOutCommand = new DelegateCommand(Logout);
//实例化命令
GoBackCmd = new DelegateCommand(() =>
{
if (journal != null && journal.CanGoBack)
journal.GoBack();
});
GoFwrdCmd = new DelegateCommand(() =>
{
if (journal != null && journal.CanGoForward)
journal.GoForward();
});
}
private void Logout()
{
App.LoginOut(provider);
}
//添加变量
private readonly IRegionManager regionManager;
private readonly IContainerProvider provider;
private IRegionNavigationJournal journal;
//添加命令
public DelegateCommand LoginOutCommand { get; set; }
public DelegateCommand<MenuBar> NavigateCmd { get; private set; }
/// <summary>
/// 导航返回命令
/// </summary>
public DelegateCommand GoBackCmd { get; private set; }
/// <summary>
/// 导航前进命令
/// </summary>
public DelegateCommand GoFwrdCmd { get; private set; }
//命令方法
private void Navigate(MenuBar obj)
{
if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
return;
regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.NameSpace, back =>
{
journal = back.Context.NavigationService.Journal;
});
}
private ObservableCollection<MenuBar> menuBars;
public ObservableCollection<MenuBar> MenuBars
{
get { return menuBars; }
set { menuBars = value; RaisePropertyChanged(); }
}
void CreatMenuBar()
{
MenuBars.Add(new MenuBar { Icon = "Home", NameSpace = "IndexView", Title = "首页" });
MenuBars.Add(new MenuBar { Icon = "FormatListChecks", NameSpace = "TodoView", Title = "待办事项" });
MenuBars.Add(new MenuBar { Icon = "Notebook", NameSpace = "MemoView", Title = "备忘录" });
MenuBars.Add(new MenuBar { Icon = "Cog", NameSpace = "SettingsView", Title = "设置" });
}
public void Configure()
{
CreatMenuBar();
//导航到主页
regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView");
}
}
}
修改xaml,增加注销按钮
<materialDesign:PopupBox Panel.ZIndex="1">
<materialDesign:PopupBox.ToggleContent>
<Image
Width="50"
Height="50"
Margin="16,0,0,0"
Source="../Images/user.jpg">
<Image.Clip>
<EllipseGeometry
Center="25,25"
RadiusX="25"
RadiusY="25" />
</Image.Clip>
</Image>
</materialDesign:PopupBox.ToggleContent>
<StackPanel>
<!--<Button Command="{Binding AppCenterCommand}" Content="个人中心"/>-->
<Button Command="{Binding LoginOutCommand}" Content="注销当前账户" />
</StackPanel>
</materialDesign:PopupBox>
首页添加用户名和时间
修改文件:Mytodo.ViewModels.IndexViewModel.cs
public DateTime CurrTime
{
get { return currTime; }
set { currTime = value; RaisePropertyChanged(); }
}
private string title;
public string Title
{
get { return title; }
set { title = value; RaisePropertyChanged(); }
}
private DateTime currTime;
private async void RefreshTimeAsync()
{
while (true)
{
await Task.Delay(1000);
CurrTime = DateTime.Now;
Title = "您好 " + AppSession.UserName + ", 现在是: " + currTime.ToString("yy-MM-dd") + " " + currTime.ToString("HH:MM:ss") + " " + currTime.ToString("ddd");
}
}
public IndexViewModel(IContainerProvider provider,
IDialogHostService dialog) : base(provider)
{
//实例化接口
this.toDoService = provider.Resolve<ITodoService>();
this.memoService = provider.Resolve<IMemoService>();
this.summService = provider.Resolve<ISummeryService>();
this.regionManager = provider.Resolve<IRegionManager>();
//初始化命令
EditMemoCmd = new DelegateCommand<MemoDto>(Addmemo);
EditTodoCmd = new DelegateCommand<ToDoDto>(Addtodo);
ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Compete);
ExecuteCommand = new DelegateCommand<string>(Execute);
NavigateCommand = new DelegateCommand<TaskBar>(Navigate);
this.dialog = dialog;
CreatBars();
RefreshTimeAsync();
}
修改bug
修改服务接口
修改ExecuteAsync()函数,修改HttpRestClient文件
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Extensions;
using RestSharp.Serializers;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share;
using MyToDo.Share.Models;
using Microsoft.AspNetCore.Http;
namespace Mytodo.Service
{
/// <summary>
/// Http本地客户端
/// </summary>
public class HttpRestClient
{
private readonly string? apiUrl;
protected readonly RestClient? client;
public HttpRestClient(string apiUrl)
{
this.apiUrl = apiUrl;
client = new RestClient();
}
/// <summary>
/// 异步执行
/// </summary>
/// <param name="baseRequest"></param>
/// <returns></returns>
public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
{
var request = new RestRequest(baseRequest.Method);
request.AddHeader("Content-Type", baseRequest.ContentType);
if (baseRequest.Parameter != null)
request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
var response = await client.ExecuteAsync(request);
var apires = JsonConvert.DeserializeObject<ApiResponse>(response.Content);
if (apires.Status)
{
///return JsonConvert.DeserializeObject<ApiResponse>(response.Content);
return new ApiResponse()
{
Status = true,
Result = JsonConvert.DeserializeObject<UserDto>(apires.Result.ToString()),
Message = ""
};
}
else
return new ApiResponse()
{
Status = false,
Result = null,
Message = response.ErrorMessage
};
}
public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
{
var request = new RestRequest(baseRequest.Method);
request.AddHeader("Content-Type", baseRequest.ContentType);
if (baseRequest.Parameter != null)
request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);
else
return new ApiResponse<T>()
{
Status = false,
Message = response.ErrorMessage
};
}
}
}
调换注册界面数据绑定
<TextBox
Margin="0,5"
md:HintAssist.Hint="请输入用户名"
DockPanel.Dock="Top"
Text="{Binding RUserDto.UserName}" />
<TextBox
Margin="0,5"
md:HintAssist.Hint="请输入账号"
DockPanel.Dock="Top"
Text="{Binding RUserDto.Account}" />