获取ViewModel中的RegionManager



在我的项目中,我使用Prism的视图和视图模型。我现在想加载另一个视图到MainWindowView中的UserControl。我读到我可以这样做:

_regionManager.RegisterViewWithRegion("MainRegion", typeof(View));

但不幸的是,我不知道如何在我的ViewModel中获得IRegionManger的实例。在我发现的所有示例中,都使用了其他变量,但没有显示它们来自何处。

This is my View:

<Window x:Class="PortfolioVisualizer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PortfolioVisualizer"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="15*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<Button Command="{Binding NavigateCommand}" CommandParameter="AddAssetView">
<StackPanel>
<Image/>
<Label Content="Add Asset"/>
</StackPanel>
</Button>
<Button Command="{Binding NavigateCommand}" CommandParameter="ConfigView">
<StackPanel>
<Image/>
<Label Content="Settings"/>
</StackPanel>
</Button>
</StackPanel>
<Grid Grid.Column="1">
<ContentControl prism:RegionManager.RegionName="MainRegion"/>
</Grid>
</Grid>
</Window>

这是我的ViewModel:

public class MainWindowViewModel : ViewModelBase
{
private readonly IRegionManager _RegionManager;
public DelegateCommand<string> NavigateCommand;

public MainWindowViewModel(IRegionManager regionManager)
{
_RegionManager = regionManager;
NavigateCommand = new DelegateCommand<string>(ExecuteNavigateCommand);
_RegionManager.RegisterViewWithRegion("MainRegion", typeof(DashboardView));
}
private void ExecuteNavigateCommand(string viewName)
{
if (string.IsNullOrWhiteSpace(viewName))
return;
_RegionManager.RequestNavigate("ContentRegion", viewName);
}
}

这是ViewModdelBase

public class ViewModelBase : BindableBase
{
public ViewModelBase()
{

}
}

(我知道ViewModelBase只是多余的,但有一些东西以后)

您让容器像任何其他依赖项一样注入区域管理器:

internal class MyViewModel
{
public MyViewModel( IRegionManager regionManager )
{
regionManager.DoSomeStuff(); // or just put it into a field for later use
}
}

注意,这只会自动工作,如果你没有手动new视图模型无论是在代码或xaml。相反,如果您使用视图模型优先(建议大多数时间),则使用本身注入的工厂(例如Func<MyViewModel> myViewModelFactory)创建它,或者如果您使用视图优先,则使用Prism的ViewModelLocator将其创建为数据上下文。

最新更新