在我的專案中,我將 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 只是多余的,但稍后會有一些東西)
uj5u.com熱心網友回復:
您讓容器像任何其他依賴項一樣注入區域管理器:
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將其創建為資料背景關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/337966.html
