使用 ViewModel WPF 从 Codehind 执行方法

Ter*_*ull 3 wpf view code-behind viewmodel

我已经在应用程序开发的中途放弃了 MVVM,只是为了推出这个应用程序。

我在后面的代码中编写了一个方法来更新数据库/数据网格等。

我的应用程序导航正在使用命令到 ViewModel 来触发一些事件,但除了一次初始化类之外,从不触及代码隐藏。

所以基本上我按下按钮一次,它使用默认的初始设置,但是一旦视图被初始化,我就不能再调用我的代码隐藏 Update() 方法。

如何从视图模型调用此代码隐藏方法?

谢谢!!

更新代码

 //Navigation ViewModel
//PaneVm.cs

public CommandExtension NewAssignmentCommand { get; set; }
    private void CreateCommands()
    {
        NewAssignmentCommand = new CommandExtension(NewAssignment, CanNewAssignment);
}
GlobalCommands.NewAssignmentCommand = NewAssignmentCommand;

private bool CanNewGroupAssignment(object obj)
    {
        return true;
    }

    private void NewGroupAssignment(object obj)
    {
        OnPropertyChanged("NewGroupAssignmentCommand");
    }


//MainVM.cs
// [Events]
    void _PaneVm_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "NewGroupAssignmentCommand")
            WorkspaceVm.CurrentVm = new NewAssignmentsVm();
}


//NewAssignmentVm.cs
//Constructor
    public NewAssignmentsVm()
    {
        var rc = new RepositoryContext();

        _RoResearchers = new ObservableCollection<Researcher>(rc.ResearcherData.GetAllResearchers());

        _QuarterDateTime = DateTime.Now;

        CreateCommands();
    }

//NewAssignment.cs
//Code-behind
//The method
private void UpdateGrid()
    {
        report_datagrid.ItemsSource = null;

        using (var rc = new RepositoryContext())
        {
            if (quarter_datepicker.SelectedDate != null)
            {
                if (!String.IsNullOrEmpty(reportType))
                    researchers = rc.ResearcherData.GetResearchersWeeksByQuarter(Convert.ToDateTime(quarter_datepicker.SelectedDate), reportType).ToList();

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新 2:

我根据这个答案解决了我的问题。我创建了一个全局操作

 public static class GlobalCommands 
 { 
 public static Action UpdateGrid { get; set; } 
 } 
Run Code Online (Sandbox Code Playgroud)

然后在我的代码隐藏构造函数中,我将值设置为 public

   MyCodeBehind() 
   { 
       GlobalCommands.UpdateGrid = new Action(() => this.UpdateGrid()); 
   } 
Run Code Online (Sandbox Code Playgroud)

不需要再次绑定到上下文。其他一切都一样。谢谢

Mer*_*aya 5

主要思想是:

class MyCodeBehind
{
   public MyCodeBehind()
   {
      Action action = new Action(()=> this.SomeMethodIWantToCall());
      var myVM = new MyVM(action); // This is your ViewModel
      this.DataContext = myVM;
   }

   private void SomeMethodIWantToCall(){...}
}

class MyVM
{
    private Action action;

    public MyVM(Action someAction)
    {
       this.action = someAction;
    }

    private void SomeMethodInVM()
    {
        this.action(); // Calls the method SomeMethodIWantToCall() in your code behind
    }
}
Run Code Online (Sandbox Code Playgroud)