关闭时以及使用MVVM更改ViewModel - C#时的功能

时间:2016-05-09 15:00:34

标签: c# wpf web-services mvvm

我有一些问题,而且我在寻找答案时遇到了一些麻烦,所以我决定将它们放在这里。

Q1:每次应用关闭时我都要调用一个函数,例如:点击退出按钮然后再做一些事情。

Q2:我在shell viewmodel中有一个控制ViewModel的menuitemcontrol,但在创建它们时我做了一些webservices请求,但想象一下我删除了一个朋友请求我更新请求viewmodel,如何从其他视图模型中调用?

编辑:场景 - 包含HomeViewModel和FriendsViewModel的ShellViewModel,我在FriendsViewModel中接受了一个朋友,当我单击Home时,从webservice获取信息的功能再次运行。 (如果我在代码隐藏中做,我会使用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向此发送消息,以便让更新再次运行(非常酷且简单的解决方案),但它没有&# 39; t work 因为不知何故我的单身人士被删除了:O

发送的消息: MessengerInstance.Send(new NotificationMessage("notification message"));

致以最诚挚的问候,

1 个答案:

答案 0 :(得分:1)

Q1 - 您使用的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>

Q2 - 此外,使用MVVM框架时也很容易。他们中的大多数都实现了Message Mediator模式。这对你来说意味着什么。这意味着你可以发送一条消息警告“请求需要更新”,一个接收器绑定到该消息,在收到消息时实现某些功能。请查看Microsoft的demo