How to call method in window (.xaml.cs) from viewmodel (.cs) without introducing new references in wpf

后端 未结 2 2062
闹比i
闹比i 2021-01-01 18:12

I\'m looking for a simple way to call a method in my Main Window, but I want to call it from my View Model. Basically, I\'m looking for some king of \"this.parent\" sort of

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 18:42

    VM should "know" nothing of your View or Window, the way VM typically "communicates" with V in WPF/MVVM is by rasing events. That way VM remains ignorant of/decoupled from the V and since VM is already DataContext of V it's not hard to subscribe to VM's event.

    Example:

    VM:

    public event EventHandler> DoSomething;
    ...
    Notify(DoSomething, new NotificationEventArgs("Message"));
    

    V:

    var vm = DataContext as SomeViewModel; //Get VM from view's DataContext
    if (vm == null) return; //Check if conversion succeeded
    vm.DoSomething += DoSomething; // Subscribe to event
    
    private void DoSomething(object sender, NotificationEventArgs e)
    {
        // Code    
    }
    

提交回复
热议问题