michaelscodingspot / WPF_MVVMC

A WPF framework for navigation between pages with MVC-like pattern
MIT License
64 stars 18 forks source link

Navigation from Code Behind #2

Closed ghost1372 closed 5 years ago

ghost1372 commented 5 years ago

hi again, @michaelscodingspot is it possible navigate from code behind? I want to navigate from my usercontrol to another usercontrol But I do not want to use the command in xaml also I do not use MVVM pattern.

michaelscodingspot commented 5 years ago

Hi,

Absolutely. From anywhere in code, you can write:

var navigationService = NavigationServiceProvider.GetNavigationServiceInstance();

navigationService.GetController<MainOperationController>().MyDashboard();
// or
navigationService.GetController("MainOperation").Navigate("MyDashboard", someParameter);
ghost1372 commented 5 years ago

Thank you dear friend And yet another question, I used the following code to open a usercontrol That I could pass the values to usercontrols. So, in which way can I pass the values again with your navigation service?

 MyDashboard.myStringVar = "new string";
 MyDashboard.myIntegerVar = 20;
 exContent.Content = new MyDashboard();
michaelscodingspot commented 5 years ago

I would suggest using the MVVM pattern here. If you're navigating to MyDashboardView, which is part of the MainOperation controller, then you can add a MyDashboardViewModel.

Navigation would happen this way:

class MyDashboardContext
{
  public string myStringVar {get; set;}
  public int myIntegerVar {get;set;}
}

// ...
var context = new MyDashboardContext()
{
  myStringVar = "new string",
  myIntegerVar = 20
};
navigationService.GetController("MainOperation").Navigate("MyDashboard", context);

In MainOperationController you can write:

public void MyDashboard(MyDashboardContext contextParmeter)
{
  ExecuteNavigation(contextParameter, null);
}

Now you'll be able to use "contextParameter" in the ViewModel:

public class MyDashboardViewModel: MVVMCViewModel
{
    public override void Initialize()
    {
        base.Initialize();
        var context = NavigationParameter as MyDashboardContext;
        Console.Writeline($"myStringVar = {context.myStringVar}, myIntegerVar = {context.myIntegerVar}");
    }
}

Once in ViewModel, you can use MVVM to bind that information. Another option would be to use mvvmc:ViewBagBinding as written in the documentation.

Michael