.NET Core 3 WPF MVVM框架 Prism系列之數據綁定

 一.安裝Prism

 

1.使用程序包管理控制檯

Install-Package Prism.Unity -Version 7.2.0.1367
也能夠去掉‘-Version 7.2.0.1367’獲取最新的版本

 2.使用管理解決方案的Nuget包

 


在上面或許咱們有個疑問?爲啥安裝prism會跟Prism.Unity有關係,咱們知道Unity是個IOC容器,而Prism自己就支持IOC,且目前官方支持幾種IOC容器:

1.且unity因爲是微軟官方的,且支持prism的組件化,由此我推薦使用prism.unity,在官方文檔中prism7不支持prism.Mef,Prism 7.1將不支持prism.Autofac
2.安裝完prism.unity就已經包含着全部prism的核心庫了,架構以下:

二.實現數據綁定

咱們先建立Views文件夾和ViewModels文件夾,將MainWindow放在Views文件夾下,再在ViewModels文件夾下面建立MainWindowViewModel類,以下:express

 

xmal代碼以下:
<Window x:Class="PrismSample.Views.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:prism="http://prismlibrary.com/"
        xmlns:local="clr-namespace:PrismSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" prism:ViewModelLocator.AutoWireViewModel="True">
    <StackPanel>
        <TextBox Text="{Binding Text}" Margin="10" Height="100" FontSize="50" Foreground="Black" BorderBrush="Black"/>
        <Button  Height="100" Width="300" Content="Click Me" FontSize="50" Command="{Binding ClickCommnd}"/>
    </StackPanel>
</Window>

 

ViewModel代碼以下:
using Prism.Commands;
using Prism.Mvvm;

namespace PrismSample.ViewModels
{
   public class MainWindowViewModel:BindableBase
    {
        private string _text;
        public string Text
        {
            get { return _text; }
            set { SetProperty(ref _text, value); }
        }

        private DelegateCommand _clickCommnd;
        public DelegateCommand ClickCommnd =>
            _clickCommnd ?? (_clickCommnd = new DelegateCommand(ExecuteClickCommnd));

        void ExecuteClickCommnd()
        {
            this.Text = "Click Me!";
        }

        public MainWindowViewModel()
        {
            this.Text = "Hello Prism!";
        }
    }
}

 

啓動程序:

 
點擊 click Me 按鈕:


能夠看到,咱們已經成功的用prism實現數據綁定了,且View和ViewModel完美的先後端分離後端

可是如今咱們又引出了另一個問題,當咱們不想按照prism的規定硬要將View和ViewModel放在Views和ViewModels裏面,又或許本身的項目取名規則各不相同怎麼辦,這時候就要用到另外幾種方法:架構

1.更改命名規則


若是,公司命名規則很變態,致使項目結構變成這樣(這種公司辭職了算了):

首先咱們在App須要引入prism,修改‘Application’爲‘prism:PrismApplication’且刪除StartupUri
xmal代碼以下:
 
<prism:PrismApplication x:Class="PrismSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             xmlns:local="clr-namespace:PrismSample">
    <Application.Resources>
         
    </Application.Resources>
</prism:PrismApplication>
 
cs後臺代碼以下:
using Prism.Unity;
using Prism.Ioc;
using Prism.Mvvm;
using System.Windows;
using PrismSample.Viewsb;
using System;
using System.Reflection;

namespace PrismSample
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        //設置啓動起始頁
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }

        //配置規則
        protected override void ConfigureViewModelLocator()
        {
            base.ConfigureViewModelLocator();
            ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
            {
                var viewName = viewType.FullName.Replace(".Viewsb.", ".ViewModelsa.OhMyGod.");
                var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
                var viewModelName = $"{viewName}Test, {viewAssemblyName}";
                return Type.GetType(viewModelName);
            });
        }
    }
}

 

上面這兩句是關鍵:

".Viewsb." 表示View所在文件夾namespace,".ViewModelsa.OhMyGod." 表示ViewModel所在namespace
var viewName = viewType.FullName.Replace(".Viewsb.", ".ViewModelsa.OhMyGod.");

  

Test表示ViewModel後綴
var viewModelName = $"{viewName}Test, {viewAssemblyName}";

 

2.自定義ViewModel註冊


咱們新建一個Foo類做爲自定義類,代碼以下:
using Prism.Commands;
using Prism.Mvvm;

namespace PrismSample
{
   public class Foo:BindableBase
    {

        private string _text;
        public string Text
        {
            get { return _text; }
            set { SetProperty(ref _text, value); }
        }

        public Foo()
        {
            this.Text = "Foo";
        }

        private DelegateCommand _clickCommnd;
        public DelegateCommand ClickCommnd =>
            _clickCommnd ?? (_clickCommnd = new DelegateCommand(ExecuteClickCommnd));

        void ExecuteClickCommnd()
        {
            this.Text = "Oh My God!";
        }
    }
}

 


修改App.cs代碼:
protected override void ConfigureViewModelLocator()
        {
            base.ConfigureViewModelLocator();
            ViewModelLocationProvider.Register<MainWindow, Foo>();
            //ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
            //{
            //    var viewName = viewType.FullName.Replace(".Viewsb.", ".ViewModelsa.OhMyGod.");
            //    var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
            //    var viewModelName = $"{viewName}Test, {viewAssemblyName}";
            //    return Type.GetType(viewModelName);
            //});
        }

 

 
運行:
 
點擊按鈕:
 

就算是不註釋修改命名規則的代碼,咱們發現運行結果仍是同樣,所以咱們能夠得出結論,app

這種直接的,不經過反射註冊的自定義註冊方式優先級會高點,在官方文檔也說明這種方式效率會高點前後端分離

且官方提供4種方式,其他三種的註冊方式以下:ide

ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), typeof(MainWindowTest)); 
ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), () => Container.Resolve<Foo>());
ViewModelLocationProvider.Register<MainWindow>(() => Container.Resolve<Foo>());

 

 
2.使用管理解決方案的Nuget包
[2. Shǐyòng guǎnlǐ jiějué fāng'àn de Nuget bāo]
2. Use Nuget package management solutions
相關文章
相關標籤/搜索