【发布时间】:2021-12-06 15:10:48
【问题描述】:
在我的项目中,我将 Prism 用于视图和视图模型。我现在想将另一个视图加载到 MainWindowView 中的 UserControl 中。我读到我可以这样做:
_regionManager.RegisterViewWithRegion("MainRegion", typeof(View));
但不幸的是,我不知道如何在我的 ViewModel 中访问 IRegionManger 的实例。在我找到的所有示例中,都使用了其他变量,但没有显示它们的来源。
这是我的观点:
<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);
}
}
这是 ViewModdelBase
public class ViewModelBase : BindableBase
{
public ViewModelBase()
{
}
}
(我知道ViewModelBase只是画蛇添足,但后面有东西)
【问题讨论】:
标签: c# wpf mvvm navigation prism