c# - 在 ViewModel 中获取 RegionManager
问题描述
在我的项目中,我将 Prism 用于视图和视图模型。我现在想将另一个视图加载到 MainWindowView 中的 UserControl 中。我读到我可以这样做:
_regionManager.RegisterViewWithRegion("MainRegion", typeof(View));
但不幸的是,我不知道如何访问IRegionManger
我的 ViewModel 中的实例。在我发现的所有示例中,都使用了其他变量,但没有显示它们的来源。
这是我的观点:
<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>
这是我的视图模型:
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);
}
}
这是 ViewModelBase
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
相反,如果您先查看模型(大部分时间推荐),请使用本身注入的工厂(例如)创建它,或者如果您先查看,则使用 PrismViewModelLocator
将其创建为数据上下文。
推荐阅读
- arrays - 为什么我的二维数组中的 x 值是垂直的而 y 值是水平的
- amazon-dynamodb - DynamoDB Query - GSI
- xamarin - Complte event for Editor behaving like Unfocussed event
- laravel - many to many relationship - save in multiple database column and retrieve
- reactjs - React native 无法从 '10' 确定 java 版本
- angular - How to get firestore timestamp
- angular - Got a sass-loader error when I upgraded my dependencies from angular 2 to angular 5
- bash - Linux date 命令生成电子邮件标头
- php - 如何用sql计算数组中的每个项目
- ios - 如何从 SKscene 检测设备旋转