[英]Do functions when closing and when changing ViewModel - C# using MVVM
我有一些问题,在寻找答案时遇到了一些麻烦,因此我决定将它们放在这里。
问题1:每次应用程序关闭时,我都必须调用一个函数,例如:单击退出按钮,然后执行某些操作。
Q2:我在shell视图模型中有一个menuitemcontrol来控制ViewModel,但是在创建它们时,我会执行一些Web服务请求,但是想象一下,我删除了一个朋友,要求我更新该视图模型中的请求,我该如何从其他地方进行调用视图模型?
编辑:场景-包含HomeViewModel和FriendsViewModel的ShellViewModel,我在FriendsViewModel中接受了一个朋友,我希望当我单击Home时可以从Web服务中获取信息的函数再次运行。 (如果我在后台进行代码操作,则可以使用Onclick [Home]> runlogin())
UpdateQ2:
public FriendsViewModel()
{
MessengerInstance.Register<NotificationMessage>(this, NotifyMe);
au = AuthSingleton.Instance.getAuthUser(); // Singleton that works like a session in the desktop App.
if (AuthSingleton.Instance.IsAuth == true)
loadFriends();
}
public void NotifyMe(NotificationMessage notificationMessage)
{
string notification = notificationMessage.Notification;
//do your work
loadFriends();
}
#endregion constructors
public async void loadFriends()
{
var response = await CommunicationWebServices.GetASM(au.idUser + "/friends", au.token);
var fh = JsonConvert.DeserializeObject<FriendsHandler>(response);
}
我决定使用评论者用户的建议,将第二个ViewModel的消息发送到此视图,以命令更新再次运行(非常酷和简单的解决方案),但是它不起作用,因为以某种方式删除了我的单身人士:O
发送的消息: MessengerInstance.Send(new NotificationMessage("notification message"));
最好的祝福,
问题1-您使用什么MVVM框架? 我知道的所有MVVM框架都实现自定义命令(也称为RelayCommands / DelegatingCommands),因此您可以将它们附加到Window事件。 另一种解决方案将在您的ViewModel中实现ClosingRequest事件的实现。 像这样:
public class BaseViewModel
{
public event EventHandler ClosingRequest;
protected void OnClosingRequest()
{
if (this.ClosingRequest != null)
{
this.ClosingRequest(this, EventArgs.Empty);
}
}
}
因此,在您的视图中,您将拥有:
public partial class MainWindow: Window
{
...
var vm = new BaseViewModel();
this.Datacontext = vm;
vm.ClosingRequest += (sender, e) => this.Close();
}
如果使用的是MVVM Light,则可以在ViewModel中执行以下操作:
public ICommand CmdWindowClosing
{
get
{
return new RelayCommand<CancelEventArgs>(
(args) =>{
});
}
}
在您的窗口中:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<command:EventToCommand Command="{Binding CmdWindowClosing}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
问题2-同样,使用MVVM框架时这很容易。 它们中的大多数实现了Message Mediator模式。 这对您意味着什么。 这意味着您可以发送一条警告“请求需要更新”的消息,并且接收者绑定到该消息,并在收到消息时执行某些操作。 看看微软的这个演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.