How do I obtain a RegionManager object in code-behind for navigation purposes in Prism?

时间:2018-04-18 17:44:17

标签: c# wpf prism prism-6

I'd like to create a custom hyperlink control that, when clicked, navigates to a region and parameters specified by bindings to properties in a parent ViewModel. Since I'd like to be able to drop this control into any arbitrary xaml, it cannot have its own ViewModel or Module Manager, which is usually how a Region Manager is obtained.

Is there a way to get a RegionManager object in code-behind, without having to inject it into a ViewModel? I see that there's a static GetRegionManager() method on the RegionManager class, but it takes a dependency property parameter that I don't understand how to use.

Why I'd like to do this in code-behind:

While I could certainly supply the constructor that allows injection of the RegionManager object into the ViewModel, I would like my new Hyperlink control to be more self-contained and independent than that. Involving the ViewModel in this manner means that the navigation is going to take place in the ViewModel, not the new Hyperlink control, which sort of defeats the purpose of having a self-contained Hyperlink control.

2 个答案:

答案 0 :(得分:0)

听起来你想要的东西与按钮的行为,但具有超链接的外观。如果是这样,我建议使用现有的WPF Button控件并将其设置为适当的样式,以显示为超链接。

如果这符合您的目的,那么无论您在何处使用控件,都可以将其绑定到命令中,无论在哪个视图模型中使用。每个视图模型都可以有一个IRegionManager(例如,通过构造函数注入),您可以使用IRegionManager.RequestNavigate来执行任何适当的导航。

作为附带好处,将逻辑保留在viewmodel中可以更容易地测试它。例如,单元测试可以在viewmodel上调用该命令,并验证是否使用适当的参数调用了IRegionManager.RequestNavigate。

答案 1 :(得分:0)

你总是可以使用CommonServiceLocator,但这只是邪恶的。此外,您希望导航在视图模型中(而不是在视图中)发生,只是为了使其可测试。如果不是这样,你可以完全放弃mvvm。

拥有HyperLinkViewModel(收到IRegionManager并且有关联的DataTemplate和/或ControlTemplate)对我来说看起来非常独立,顺便说一下。只需将其作为另一个视图模型的属性公开,您就可以使用工作超链接。

在某种程度上,视图模型 DataTemplate的代码隐藏。