想要盡快啟動和運行嗎?跟着作者馬上行動!
注意:如果您要查找示例應用程序,請下載源代碼並查看"示例"文件夾。
以下說明將設置一個最小骨架項目。
- 自動選項
- .NET Framework
注意:如果項目對 NuGet 包使用包引用,或者使用的是 VS2013 或更早版本,則此操作將不起作用。請改為按照下面的"手動選項"部分操作。
如果您不熟悉 Stylet(並且您運行的是 VS2015 或更高版本),這是最簡單的入門方法。
打開 Visual Studio,然后創建一個新的WPF Application項目
打開"NuGet"(右鍵單擊項目 ->管理 NuGet 包"),搜索“Stylet.Start”,然后安裝該包。
這將為您提供一個工作框架項目。
安裝完成后,卸載 Stylet.Start。
祝您編碼愉快!
- .NET Core
對於 .NET Core 項目,最快的入門方法是使用 Stylet 的模板。
打開要在其中創建新項目的命令窗口,然后使用以下命令安裝 Stylet 模板:
dotnet new -i Stylet.Templates
然后使用以下命令創建新項目:
dotnet new stylet -o MyStyletProject
- 手動選項
如果您不想使用該包,而希望創建自己的框架項目,請按照本節中的說明進行操作。
打開 Visual Studio,然后創建一個新的WPF Application項目,
打開"NuGet"(右鍵單擊項目 ->管理 NuGet 包"),然后安裝Stylet包。
首先,刪除MainWindow.xaml和MainWindow.xaml.cs ,您並不需要它們。
接下來,您將需要一個根視圖和一個 ViewModel。視圖必須是Window,但沒有其他限制。
<Window x:Class="Stylet.Samples.Hello.RootView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<TextBlock>Hello, World</TextBlock>
</Window>
ViewModel如下:
public class RootViewModel
{
}
接下來,您將需要一個引導程序。現在,您不需要任何特殊的東西 - 只需要一些東西來識別您的 RootViewModel。稍后,你將能夠在此處配置 IoC 容器以及其他應用程序級內容。
public class Bootstrapper : Bootstrapper<RootViewModel>
{
}
最后,您需要將 Stylet 添加到App.xaml的資源中,並確定為您在上面創建的引導程序。
它應該看起來像這樣:
<Application x:Class="Stylet.Samples.Hello.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="https://github.com/canton7/Stylet"
xmlns:local="clr-namespace:Stylet.Samples.Hello">
<Application.Resources>
<s:ApplicationLoader>
<s:ApplicationLoader.Bootstrapper>
<local:Bootstrapper/>
</s:ApplicationLoader.Bootstrapper>
</s:ApplicationLoader>
</Application.Resources>
</Application>
就是這樣!運行它,你會得到一個帶有"Hello World"的窗口。
- 應用程序加載器
值得注意的是,上面是一個資源字典子類。這允許將Stylet加載到內置資源中。您也可以選擇不加載 Stylet 的資源,如下所示:
<s:ApplicationLoader>
<s:ApplicationLoader LoadStyletResources="False">
...
</s:ApplicationLoader>
如果您想將自己的資源/資源詞典添加到應用程序中,最簡單的方法是這樣的:
<Application.Resources>
<s:ApplicationLoader>
<s:ApplicationLoader.Bootstrapper>
<local:Bootstrapper/>
</s:ApplicationLoader.Bootstrapper>
<Style x:Key="MyResourceKey">
...
</Style>
<s:ApplicationLoader.MergedDictionaries>
<ResourceDictionary Source="MyResourceDictionary.xaml"/>
</s:ApplicationLoader.MergedDictionaries>
</s:ApplicationLoader>
</Application.Resources>
如果對上面的配置感到不爽,也可以這樣做:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<s:ApplicationLoader>
<s:ApplicationLoader.Bootstrapper>
<local:Bootstrapper/>
</s:ApplicationLoader.Bootstrapper>
</s:ApplicationLoader>
<ResourceDictionary Source="MyResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style x:Key="MyResourceKey">
...
</Style>
</ResourceDictionary>
</Application.Resources>