Reputation: 1202
In my WPF application I need to get View based on MyViewModel and show it using ReactiveUI and can't figure out how to do it.
So long all got is this lines:
Locator.CurrentMutable.Register(() => new MyView(), typeof(IViewFor<MyViewModel>));
var ViewModel = (MyViewModel)Locator.CurrentMutable.GetService(typeof(MyViewModel));
Then I should use some "Router" but what exactly is this?
Upvotes: 3
Views: 2323
Reputation: 2888
I am going to use samples from the book You, I and Reactive UI. Here is the GIT repository https://github.com/kentcb/YouIandReactiveUI
In terms of using the RoutedViewHost WPF control you can do the following (which you seem to be wanting to use based on what you mentioned)
First I have some sort of boot strapper class where I do my Splat registrations. On that I will have create a object of RoutingState. This is used by the RoutedViewHost.
protected Bootstrapper()
{
RegisterMyDIStuff();
this.Router = new RoutingState();
resolver.RegisterConstant<IScreen>(this);
this
.Router
.NavigateAndReset
.Execute(new StartViewModel())
.Subscribe()
.DisposeWith(this.disposable);
}
/// <inheritdoc />
public RoutingState Router { get; }
All views must implement the interface IViewFor and be registered in Splat. Eg: resolver.Register(() => new LoginView(), typeof(IViewFor));
In your XAML file declare the RoutedViewHost
<rxui:RoutedViewHost
x:Name="routedViewHost"
Grid.Row="1"
Grid.ColumnSpan="3"/>
Then in your code behind for the view's code behind:
public MainWindow()
{
this.routedViewHost.Router = BootStrapper.Router;
}
Then you View Models have to derive off IRoutableViewModel
public MainViewModel(IScreen hostScreen = null)
{
this.HostScreen = hostScreen ?? Locator.Current.GetService<IScreen>();
}
/// <inheritdoc />
public string UrlPathSegment => "Main";
/// <inheritdoc />
public IScreen HostScreen { get; }
Then when you want to navigate to another ViewModel's View you can:
await this.HostScreen.Router.NavigateAndReset.Execute(new LogoutViewModel());
Upvotes: 3