C#-WPF-Prism.DryIoc-【1】環境搭建
阿新 • • 發佈:2022-04-20
我的環境:VS2022、.Net6.0
【1】建立wpf應用程式
【2】建立兩個資料夾 Views 和ViewModels,並在對應的資料夾中新增MainView(將把它作為啟動視窗)和MainViewModel
【3】安裝Nuget包 Prism.DryIoc 可通過以下兩種方式的任意一種安裝
【4】修改App.xaml 將下圖(4.1)修改為圖(4.2)
圖(4.1):
圖(4.2):
<prism:PrismApplication x:Class="Wpf_Prsim.DryIoc_EnvironmentConfiguration.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Wpf_Prsim.DryIoc_EnvironmentConfiguration" xmlns:prism="http://prismlibrary.com/"> <Application.Resources></Application.Resources> </prism:PrismApplication>
變化的內容:將Application類改為了PrismApplication,刪除了StartupUri
【5】修改App.xaml.cs 將下圖(5.1)修改為圖(5.2)
圖(5.1):
圖(5.2):
/// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication {protected override Window CreateShell() { return Container.Resolve<MainView>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } }
變化的類容
1.將App繼承於PrismApplication(您也可以不用寫繼承)並實現了兩個抽象成員(快捷鍵 Alt+Enter Enter,如果沒有實現抽象類的提示請先編譯一下專案)
2.添加了一行程式碼 return Container.Resolve<MainView>(); 從容器中取出MainView作為主視窗
3.注意新增對應的名稱空間(快捷鍵 Alt+Enter Enter)
【6】啟動專案
可以看到 MainView已經正常啟動,如果希望自動繫結上下文到MainViewModel只需要在MainView.xaml 中新增
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
<Window x:Class="Wpf_Prsim.DryIoc_EnvironmentConfiguration.Views.MainView" 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:Wpf_Prsim.DryIoc_EnvironmentConfiguration.Views" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d" Title="MainView" Height="450" Width="800"> <Grid> </Grid> </Window>
完成!謝謝。