2020年4月24日 星期五

Blazor 使用 資料模型 來顯示資料表關聯的集合資料

Blazor 使用 資料模型 來顯示資料表關聯的集合資料

在上一篇文章 在 Blazor 專案內使用 Syncfusion 的 DataGrid 套件 中,使用 Syncfusion 的 DataGrid 元件顯示這些資料,在這將會需要把資料庫內表格 Table 的關聯紀錄,使用 Syncfusion DataGrid 來顯示出來,這裡暫時先不使用 AutoMapper 來實現這樣的功能,而是建立一個資料模型類別,且搭配使用 LINQ 來做到。
這個說明專案的原始碼位於 bzSyncfusionDataGridModel

修正 DataGrid 元件

  • 打開 [Pages] 資料夾內的 [index.razor] 檔案,輸入底下 HTML 標記與程式碼
@page "/"
@using bzEntityFrameworkCore.Models
@using Microsoft.EntityFrameworkCore
@inject ContosoUniversityContext Context

<h1>Hello, Entity Framework Core</h1>

<button class="btn btn-primary" @onclick="LoadData">讀取資料庫</button>

<SfGrid DataSource="@records">
    <GridColumns>
        <GridColumn Field=@nameof(RowData.CourseId) HeaderText="序號" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(RowData.Title) HeaderText="課程名稱" Width="150"></GridColumn>
        <GridColumn Field=@nameof(RowData.Credits) HeaderText=" Credits" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
        <GridColumn Field=@nameof(RowData.Name) HeaderText="科系" TextAlign="TextAlign.Right" Width="120"></GridColumn>
    </GridColumns>
</SfGrid>
@code{
    class RowData
    {
        public int CourseId { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public string Name { get; set; }
    }

    List<RowData> records = new List<RowData>();
    async void LoadData(MouseEventArgs e)
    {
        var rows = await Context.Course.Include(x => x.Department).ToListAsync();

        // 這裡使用 LINQ 宣告式語言來實現
        var query = from c in rows
                    select new RowData
                    {
                        CourseId = c.CourseId,
                        Title = c.Title,
                        Credits = c.Credits,
                        Name = c.Department.Name
                    };
        records = query.ToList();

        //// 這裡使用 LINQ 延伸方法來實現
        //records = rows.Select<Course, RowData>((x, y) =>
        //new RowData
        //{
        //    CourseId = x.CourseId,
        //    Title = x.Title,
        //    Credits = x.Credits,
        //    Name = x.Department.Name
        //}).ToList();

        StateHasChanged();
    }
}
在此將建立一個 RowData 類別,該類別將會用於顯示每筆紀錄所用的資料模型,而在資料庫那哩,因為要取得 Department 這個關聯資料表內的相關紀錄,因此,需要使用 Include(x => x.Department) 這個方法呼叫,如此,在資料庫端將會執行 Table Join 的查詢動作;另外,當資料查詢出來之後,將會透過 LINQ 的功能,將資料庫讀取出來的紀錄內容,轉換成為資料模型 RowData 型別的物件。
  • 執行這個專案,將會看到使用 Syncfusion DataGrid 元件顯示出底下的輸出內容,若有看到,就代表已經成功讀取資料庫紀錄了。




2020年4月23日 星期四

在 Blazor 專案內使用 Syncfusion 的 DataGrid 套件

在 Blazor 專案內使用 Syncfusion 的 DataGrid 套件

在上一篇文章 使用 Blazor 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫 中,說明如何在 Blazor 專案內,透過 C# 程式碼來讀取 Entity Framework 資料庫內的資料表紀錄,在這篇文章中,將會延續上一個專案程式碼,不過,在這裡將會使用 Syncfusion 的 DataGrid 元件顯示這些資料。
這個說明專案的原始碼位於 bzSyncfusionDataGrid

使用 Syncfusion 的準備工作

  • 上一篇文章的專案,也就是 bzEntityFrameworkCore
  • 滑鼠右擊專案 [相依性] > [管理 NuGet 套件]
  • 搜尋 [Syncfusion.Blazor] 套件,安裝到專案內
  • 在 [Pages] 資料夾內找到 [_Host.cshtml] 檔案,並且打開該檔案
  • 在 <head> 區段內加入底下的宣告
@*底下為要使用 Syncfusion 相關套件需要用到的 css 內容*@
<link href="_content/Syncfusion.Blazor/styles/fabric.css" rel="stylesheet" />
<!---CDN--->
@*<link href="https://cdn.syncfusion.com/blazor/18.1.44/styles/fabric.css" rel="stylesheet" />*@

@*底下為要相容於 IE11 要做的宣告*@
<script src="https://github.com/Daddoon/Blazor.Polyfill/releases/download/3.0.1/blazor.polyfill.min.js"></script>
  • 在專案根目錄下打開 [_Imports.razor] 檔案
  • 加入這行程式碼到最後面 @using Syncfusion.Blazor.Grids
  • 在專案根目錄下打開 [Startup.cs] 檔案
  • 找到 [ConfigureServices] 方法,註冊 Syncfusion 會用到的相關服務,使用該行敘述 services.AddSyncfusionBlazor();

開始使用 DataGrid 元件

  • 打開 [Pages] 資料夾內的 [index.razor] 檔案,輸入底下 HTML 標記與程式碼
@page "/"
@using bzEntityFrameworkCore.Models
@using Microsoft.EntityFrameworkCore
@inject ContosoUniversityContext Context

<h1>Hello, Entity Framework Core</h1>

<button class="btn btn-primary" @onclick="LoadData">讀取資料庫</button>

<SfGrid DataSource="@records">

</SfGrid>
@code{
    List<Course> records = new List<Course>();
    async void LoadData(MouseEventArgs e)
    {
        records = await Context.Course.ToListAsync();
        StateHasChanged();
    }
}
  • 執行這個專案,將會看到使用 Syncfusion DataGrid 元件顯示出底下的輸出內容,若有看到,就代表已經成功讀取資料庫紀錄了。



2020年4月22日 星期三

使用 Blazor 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫

使用 Blazor 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫

在上一篇文章 使用 Console 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫 中,說明如何透過 C# 程式碼來讀取 Entity Framework 資料庫內的資料表紀錄,在這篇文章中,將會建立一個 Blazor 專案,在此專案內的 Blazor 元件 Component 來存取資料庫到的資料。
這個說明專案的原始碼位於 bzEntityFrameworkCore

建立 .NET Core 之 Console 專案

  • 打開 Visual Studio 2019
  • 點選右下方的 [建立新的專案] 按鈕
  • [建立新專案] 對話窗將會顯示在螢幕上
  • 從[建立新專案] 對話窗的中間區域,找到 [Blazor 應用程式] 這個專案樣板選項,並且選擇這個項目
  • 點選右下角的 [下一步] 按鈕
  • 現在 [設定新的專案] 對話窗將會出現
  • 請在這個對話窗內,輸入適當的 [專案名稱] 、 [位置] 、 [解決方案名稱]
    在這裡請輸入 [專案名稱] 為 bzEntityFrameworkCore
  • 完成後,請點選 [建立] 按鈕
  • 當出現 [建立新的 Blazor 應用程式] 對話窗的時候
  • 請選擇最新版本的 .NET Core 與 [Blazor 伺服器應用程式]
  • 完成後,請點選 [建立] 按鈕
  • 稍微等會一段時間,專案將會建立起來

安裝需要用到的套件

建立資料庫模型

  • 點選功能表 [工具] > [NuGet 套件管理員] > [套件管理器主控台]
  • 在 [套件管理器主控台] 內輸入底下指令
Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ContosoUniversity;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
其中關於上述指定中雙引號內的內容,請打開 [SQL Server 物件總管] ,點選到 資料庫伺服器的節點,接著,查看 [屬性] 視窗內的 [連接字串],將其屬性值複製起來,貼上到雙引號內
  • 完成後,按下 [Enter] 按鍵,執行這個命令
  • 此時便可以在 Visual Studio 檔案總館內,看到有 Models 資料夾產生,而在該資料夾內也產生了許多檔案出來

建立 資料庫連接字串

  • 打開 專案根目錄下的 [appsettings.json] 檔案
  • 在該檔案內加入 [ConnectionStrings] 屬性值的宣告,如同底下內容
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ContosoUniversityContext": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ContosoUniversity;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

註冊要使用的 Entity Framework Core 的相關服務

  • 打開 專案根目錄下的 [Startup.cs] 檔案
  • 在 [ConfigureServices] 方法內,加入這行敘述 services.AddDbContext<ContosoUniversityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ContosoUniversityContext"))); ,完成後的 [ConfigureServices] 方法如下:
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
    services.AddDbContext<ContosoUniversityContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("ContosoUniversityContext")));
}

開始使用 Entity Framework Core 來讀取資料庫

  • 打開 [Pages] 資料夾內的 [index.razor] 檔案,輸入底下 HTML 標記與程式碼
@page "/"
@using bzEntityFrameworkCore.Models
@using Microsoft.EntityFrameworkCore
@inject ContosoUniversityContext Context

<h1>Hello, Entity Framework Core</h1>

<button class="btn btn-primary" @onclick="LoadData">讀取資料庫</button>
@foreach (var item in records)
{
    <div>@item</div>
}
@code{
    List<string> records = new List<string>();
    async void LoadData(MouseEventArgs e)
    {
       var allCourse = await Context.Course.ToListAsync();
        foreach (var item in allCourse)
        {
            records.Add(item.Title);
        }
    }
}
  • 執行這個專案,將會看到底下的輸出內容,若有看到,就代表已經成功讀取資料庫紀錄了。



2020年4月21日 星期二

使用 Console 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫


使用 Console 專案與 Entity Freamework Core 讀取已經存在的 Contoso University 資料庫

在上一篇文章 使用 Visual Studio 建立 Contoso University 資料庫 中,說明如何透過 Visual Studio 2019 來建立一個本機 localdb 的資料庫,而在這篇文章中,將會透過 Visual Studio 建立一個 Console 應用程式,使用 Entity Framework Core 來讀取這個已經存在的資料庫內的資料表紀錄內容。
這個說明專案的原始碼位於 DBEntityFrameworkCore

建立 .NET Core 之 Console 專案

  • 打開 Visual Studio 2019
  • 點選右下方的 [建立新的專案] 按鈕
  • [建立新專案] 對話窗將會顯示在螢幕上
  • 從[建立新專案] 對話窗的中間區域,找到 [主控台應用程式] 這個專案樣板選項,並且選擇這個項目
  • 點選右下角的 [下一步] 按鈕
  • 現在 [設定新的專案] 對話窗將會出現
  • 請在這個對話窗內,輸入適當的 [專案名稱] 、 [位置] 、 [解決方案名稱]
    在這裡請輸入 [專案名稱] 為 DBEntityFrameworkCore
  • 完成後,請點選 [建立] 按鈕
  • 稍微等會一段時間,專案將會建立起來

安裝需要用到的套件

建立資料庫模型

  • 點選功能表 [工具] > [NuGet 套件管理員] > [套件管理器主控台]
  • 在 [套件管理器主控台] 內輸入底下指令
Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ContosoUniversity;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
其中關於上述指定中雙引號內的內容,請打開 [SQL Server 物件總管] ,點選到 資料庫伺服器的節點,接著,查看 [屬性] 視窗內的 [連接字串],將其屬性值複製起來,貼上到雙引號內
  • 完成後,按下 [Enter] 按鍵,執行這個命令
  • 此時便可以在 Visual Studio 檔案總館內,看到有 Models 資料夾產生,而在該資料夾內也產生了許多檔案出來

開始使用 Entity Framework Core 來讀取資料庫

  • 打開 Program.cs 檔案,輸入底下程式碼
using DBEntityFrameworkCore.Models;
using System;

namespace DBEntityFrameworkCore
{
    class Program
    {
        static void Main(string[] args)
        {
            ContosoUniversityContext ContosoUniversityContext = new ContosoUniversityContext();
            foreach (var item in ContosoUniversityContext.Course)
            {
                Console.WriteLine($"{item.Title}");
            }
        }
    }
}
  • 執行這個專案,將會看到底下的輸出內容,若有看到,就代表已經成功讀取資料庫紀錄了。
Calculus
Chemistry
Composition
Literature
Trigonometry
Microeconomics
Macroeconomics



2020年4月20日 星期一

使用 Visual Studio 建立 Contoso University 資料庫

使用 Visual Studio 建立 Contoso University 資料庫教學

在這篇文章,將會說明如何透過 Visual Studio 2019 來建立一個本機 localdb 的資料庫,在這裡將會使用 Contoso Unsiver 這個範例資料庫做為說明。

建立本機開發用的資料庫

  • 首先,打開 Visual Studio 2019 開發工具
  • 確認功能表的 [檢視] > [SQL Server 物件管理員] 選項有勾選
  • 此時,將會看到 [SQL Server 物件管理員] 視窗出現
  • 展開 [SQL Server 物件管理員] 節點 [SQL Server] > [(localdb)\MSSQLLocalDB...] > [資料庫]
  • 滑鼠右擊該 [資料庫] 節點,選擇 [加入新的資料庫]
  • 當 [建立資料庫] 對話窗出現的時候,請在 [資料庫名稱] 欄位內輸入 [ContosoUniversityCore]
  • 完成後,點選 [確定] 按鈕
  • 從 [SQL Server 物件管理員] 視窗內,將會看到 [ContosoUniversity] 資料庫已經建立好了
  • 此時可以從 [SQL Server 物件管理員] 內看到 [ContosoUniversity] 資料庫顯示出來了
  • 滑鼠右擊該資料庫節點,選擇 [新增查詢]
  • 當看到 [SQLQuery1.sql] 視窗出現之後,輸入這裡 Contoso Unsiver 所看到的 SQL 指令,完成後,點選左上方的 綠色三角形,執行這些 SQL 指令
  • 現在,請重新整理該資料庫節點,便會看到這個 [ContosoUniversity] 資料庫節點內的 資料表 節點內,已經有產生出相關資料表了。



2020年4月15日 星期三

WPF Prism 3 - 首次使用 Module 與 Prism 開發框架來製作一個 Hello World 教學說明程式

WPF Prism 3 - 首次使用 Module 與 Prism 開發框架來製作一個 Hello World 教學說明程式

在這篇文章,將會使用 Prism 中的 Module 模組功能,實作第一篇文章的 Hello World 相同功能,因此,在這裡將會建立一個類別庫,將相關 View & ViewModel 都建立在這個類別庫內。
這個說明專案的原始碼位於 WPFPrismHelloWorldWithModule

準備工作

  • 首先,先要安裝 [Prism Template Pack] 到 Visual Studio 2019 內
  • 打開 Prism Template Pack 擴充功能網站
  • 下載並且安裝這個擴充功能

建立 WPF for Prism 的專案

  • 打開 Visual Studio 2019
  • 點選右下方的 [建立新的專案] 按鈕
  • [建立新專案] 對話窗將會顯示在螢幕上
  • 從[建立新專案] 對話窗的中間區域,找到 [Prism Blank App (WPF)] 這個專案樣板選項,並且選擇這個項目
    若沒有看到這個選項,則表示你的 Visual Studio 2019 開發環境中,還沒有安裝 Prism Template Pack 擴充功能
  • 點選右下角的 [下一步] 按鈕
  • 現在 [設定新的專案] 對話窗將會出現
  • 請在這個對話窗內,輸入適當的 [專案名稱] 、 [位置] 、 [解決方案名稱]
    在這裡請輸入 [專案名稱] 為 WPFPrismHelloWorld
  • 在最下方的 [架構] 部分,建議選取最新的 [.NET Framework 4.8]
  • 完成後,請點選 [建立] 按鈕
  • 當出現 [PRISM PROJECT WIZARD] 對話窗的時候
  • 請在 [Select Container] 選擇容器這個欄位之下拉選單,選擇你要使用的 DI 相依性注入容器,我個人習慣使用 Unity 這個 Ioc 容器
  • 之後,點選 [CREATE PROJECT] 這個按鈕
稍微等會一段時間,具有 Prism 開發框架的 WPF 專案將會建立起來

建立要設計 Module 的類別庫專案 - WPF 使用者控制項類別庫 (.NET Framework)

  • 滑鼠右擊方案節點,選擇 [加入] > [新增專案]
  • 當 [新增專案] 對話出現之後
  • 找到並且點選 [WPF 使用者控制項類別庫 (.NET Framework)]

    請注意

    這裡需要找到的是 使用 C# 程式語言,並且是 .NET Framework 用的 [WPF 使用者控制項類別庫 (.NET Framework)],這不是一般的 [類別庫 (.NET Framework)]
  • 選擇完後,點選 [下一步] 按鈕
  • 在 [專案名稱] 欄位中,輸入 HostModule
  • 點選 [建立] 按鈕

加入 WPF 套件

  • 滑鼠右擊剛剛建立的專案節點
  • 選擇 [管理 NuGet 套件]
  • 找到 [Prism.Wpf] 這個套件,並且安裝起來

在剛剛建立的專案中,加入兩個 View 與進行 Module 類別設計

  • 滑鼠右擊剛剛建立的專案,選擇 [加入] > [新增資料夾],建立 Views & ViewModels 這兩個資料夾
  • 滑鼠右擊 [Views] 資料夾
  • 選擇 [加入] > [新增項目]
  • 此時,[新增項目] 對話窗將顯示出來
  • 請在該對話窗的左方,展開節點到 [已安裝] > [Visual C#] > [Prism] > [WPF]
  • 在中間區域選擇 [Prism UserControl (WPF)] 選項
  • 在下方名稱欄位輸入 MyView
  • 最後點選 [新增] 按鈕
此時,將會看到該專案的 [Views] 資料夾內新產生了一個 [MyView.xaml] 這個檔案,另外,在 [ViewModel] 資料夾內也產生了一個 [MyViewViewModel] 這個類別檔案。
打開 [MyView.xaml] 檔案,填入底下 XAML 標記宣告
<UserControl x:Class="HostModule.Views.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid Background="LightGreen">
        <TextBlock Text="Hello World" FontSize="48" Foreground="HotPink"/>
    </Grid>
</UserControl>
接下來,繼續產生一個 YourView 檢視
  • 首先,滑鼠右擊 [Views] 資料夾
  • 選擇 [加入] > [新增項目]
  • 此時,[新增項目] 對話窗將顯示出來
  • 請在該對話窗的左方,展開節點到 [已安裝] > [Visual C#] > [Prism] > [WPF]
  • 在中間區域選擇 [Prism UserControl (WPF)] 選項
  • 在下方名稱欄位輸入 YourView
  • 最後點選 [新增] 按鈕
此時,將會看到該專案的 [Views] 資料夾內新產生了一個 [YourView.xaml] 這個檔案,另外,在 [ViewModel] 資料夾內也產生了一個 [YourViewViewModel] 這個類別檔案。
打開 [YourView.xaml] 檔案,填入底下 XAML 標記宣告
<UserControl x:Class="HostModule.Views.YourView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid Background="Yellow">
        <TextBlock Text="Thank You" FontSize="48" Foreground="LightBlue"/>
    </Grid>
</UserControl>
  • 滑鼠右擊這個專案節點,選擇 [加入] > [類別]
  • 當 [新增項目] 對話窗出現後,在下方的 [名稱] 欄位中輸入 HostModuleModule
  • 將底下的 C# 程式碼,替換掉剛剛產生的檔案內容
using HostModule.Views;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HostModule
{
    public class HostModuleModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<MyView>();
            containerRegistry.RegisterForNavigation<YourView>();
        }
    }
}

修正主專案並加入這個模組

  • 滑鼠右擊主專案 (也就是這個 WPFPrismHelloWorldWithModule 專案) 內的 [參考] > [加入參考]
  • 當 [參考管理員] 對話窗出現之後,勾選 [HostModule] 這個節點
  • 點選 [確定] 按鈕
  • 在該專案根目錄下,找到 App.xaml 這個檔案節點
  • 展開該節點,將會看到一個 [App.xaml.cs] 這個節點
  • 滑鼠雙擊打開 [App.xaml.cs] 這個節點
  • 建立一個覆寫 ConfigureModuleCatalog 方法
  • 將該方法修改成為底下的程式碼
using WPFPrismHelloWorldWithModule.Views;
using Prism.Ioc;
using Prism.Modularity;
using System.Windows;

namespace WPFPrismHelloWorldWithModule
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<HostModule.HostModuleModule>();
        }
    }
}

設計 Shell 頁面架構

  • 在 [Views] 資料夾內,找到並打開 [MainWindow.xaml] 檔案
  • 將底下的 XAML 標記宣告,替換掉這個檔案原先內容
<Window x:Class="WPFPrismHelloWorldWithModule.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525">
    <Grid Background="LightGray">
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel
            HorizontalAlignment="Center"
            Orientation="Horizontal">
            <Button Command="{Binding SayHiCommand}" Width="150">Hi</Button>
            <Button Command="{Binding ThankYouCommand}" Width="150">Thank You</Button>
            <Button Command="{Binding RemoveCommand}" Width="150">Remove</Button>
        </StackPanel>
        <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" />
    </Grid>
</Window>
  • 在 [ViewModels] 資料夾內,找到並打開 [MainWindowViewModel.cs] 檔案
  • 使用底下 C# 程式碼替換掉原先內容
using HostModule.Views;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;

namespace WPFPrismHelloWorldWithModule.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _title = "Prism Application";
        private readonly IRegionManager regionManager;

        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }
        public DelegateCommand SayHiCommand { get; set; }
        public DelegateCommand RemoveCommand { get; set; }
        public DelegateCommand ThankYouCommand { get; set; }
        public MainWindowViewModel(IRegionManager regionManager, IContainerExtension container)
        {
            SayHiCommand = new DelegateCommand(() =>
            {
                IRegion region = regionManager.Regions["ContentRegion"];
                region.RemoveAll();
                var view = container.Resolve<MyView>();
                region.Add(view);
            });
            ThankYouCommand = new DelegateCommand(() =>
            {
                IRegion region = regionManager.Regions["ContentRegion"];
                region.RemoveAll();
                var view = container.Resolve<YourView>();
                region.Add(view);
            });
            RemoveCommand = new DelegateCommand(() =>
            {
                IRegion region = regionManager.Regions["ContentRegion"];
                region.RemoveAll();
            });
        }
    }
}

執行與測試

現在可以執行這個使用 Prism 開發的 WPF 專案,看看是不是如同第一篇文章規劃的一樣方式來進行運作。