天天看點

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

大白技術控,

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

之前時間一直在使用Caliburn.Micro這種應用了MVVM模式的WPF架構做開發,是時候總結一下了。

Caliburn.Micro(Caliburn.Micro架構概述 - https://blog.csdn.net/lzuacm/article/details/78886436) 是一個輕量級的WPF架構,簡化了WPF中的不少用法,推薦做WPF開發時優先使用。

真正快速而熟練地掌握一門技術就可以嘗試着用最快的速度去建構一個玩具項目(Toy project),然後不斷地優化、重構之。比如本文将介紹如何使用Caliburn.Micro v3.2開發出一個簡單的電腦,裡面用到了C#中的async異步技術,Caliburn.Micro中的Conductor等等~

Step 1: 在VS中建立WPF項目

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

Step 2: 使用NuGet包管理工具為目前項目安裝Caliburn.Micro

對于Caliburn.Micro 1.x和2.x版,隻能使用.dll,需手動給項目加Reference。而3.0以後的版本可使用NuGet包管理工具來管理,安裝和解除安裝既友善又徹底,推薦使用。(ps: NuGet之于Visual Studio(C++, C#等), 猶pip之于Python, npm之于node, maven之于Java, gem之于Ruby等等)

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

Step 3: 架構搭建

  1. 删除項目根目錄下的MainWindow.xaml
  2. 按下圖調整App.xaml

    删除語句StartupUri="MainWindow.xmal"。

    從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦
  3. 填充Application.Resources
<Application.Resources>
         <ResourceDictionary>
             <ResourceDictionary.MergedDictionaries>
                 <ResourceDictionary>
                     <local:Bootstrapper x:Key="bootstrapper"/>
                 </ResourceDictionary>
             </ResourceDictionary.MergedDictionaries>
         </ResourceDictionary>
    </Application.Resources>
           

   4 . 建立Bootstrapper類

然後讓其繼承自BootstrapperBase類,并加上構造函數,另外再重寫函數OnStartup即可。

using System.Windows;
using Caliburn.Micro;
using CaliburnMicro_Calculator.ViewModels;

namespace CaliburnMicro_Calculator
{
    public class Bootstrapper : BootstrapperBase
    {
        public Bootstrapper()
        {
            Initialize();
        }

        protected override void OnStartup(object obj, StartupEventArgs e)
        {
            DisplayRootViewFor<ShellViewModel>();
        }
    }
}

           

   5 . 在項目目錄下建立Models, ViewModels, Views這3個檔案夾

在ViewModel檔案夾中添加ShellViewModel.cs,并建立Left, Right和Result這3個屬性。

需要注意的是 ShellViewModel.cs需要繼承類 Screen 和 INotifyPropertyChanged (用于感覺并同步所綁定屬性的變化),ShellViewModel具體代碼為:

using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Micro;

namespace CaliburnMicro_Calculator.ViewModels
{
    public class ShellViewModel : Screen, INotifyPropertyChanged
    {
        private double _left;
        private double _right;
        private double _result;

        public double Left
        {
            get { return _left; }
            set
            {
                _left = value;
                NotifyOfPropertyChange();
            }
        }

        public double Right
        {
            get { return _right; }
            set
            {
                _right = value;
                NotifyOfPropertyChange();
            }
        }

        public double Result
        {
            get { return _result; }
            set
            {
                _result = value;
                NotifyOfPropertyChange();
            }
        }
}
           

說明: 最開始布局xaml時,設計位置時采用的是左(operand 1), 中(operand 2), 右(result),于是屬性值使用了Left, Right和Result。

Step 4: 設計XAML并綁定屬性

在Views檔案夾中建立Window,命名為ShellView.xaml,在Views檔案夾下建立子檔案夾Images,用于存放+,-,*,/這4種操作對應的小圖示,其具體代碼如下:

<Window x:Class="CaliburnMicro_Calculator.Views.ShellView"
        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:CaliburnMicro_Calculator.Views"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="Calculator" SizeToContent="Height" Width="240">

    <StackPanel Background="Beige">
        <StackPanel Orientation="Horizontal">
            <Label Margin="10"
                   Target="{Binding ElementName=left}">
                Operand _1:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     x:Name="left"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Margin="10"
                   Target="{Binding ElementName=right}">
                Operand _2:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     x:Name="right"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button Margin="10"
                    x:Name="btnPlus" 
                    cal:Message.Attach="[Event Click]=[Action Plus(left.Text, right.Text):result.Text]">
                <Image Source="Images/op1.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnMinus" 
                    cal:Message.Attach="[Event Click]=[Action Minus(left.Text, right.Text):result.Text]">
                <Image Source="Images/op2.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnMultiply" 
                    cal:Message.Attach="[Event Click]=[Action Multipy(left.Text, right.Text):result.Text]">
                <Image Source="Images/op3.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnDivide" IsEnabled="{Binding Path=CanDivide}"
                    cal:Message.Attach="[Event Click]=[Action Divide(left.Text, right.Text):result.Text]">
                <Image Source="Images/op4.ICO"/>
            </Button>

        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Margin="10">
                Answer:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     Text ="{Binding Path=Result, StringFormat={}{0:F4}}" IsReadOnly="True" />
        </StackPanel>
    </StackPanel>
</Window>
           

說明:對操作數Operand _1和Operand _2,按Alt鍵+數字可以選中該處,這是WPF的一個特殊用法。由于計算結果不希望被修改,于是加上了屬性

IsReadOnly="True"

Step 5: 設計并綁定事件

由于暫時隻打算實作+, -, *, /四種操作,于是我們隻需建立相應的4個函數即可,由于除數是0這個操作不允許,于是需再加個判斷函數CanDivide。

Caliburn.Micro中綁定事件的寫法是:

cal:Message.Attach="[Event E]=[Action A]"

(E是操作,比如Click, MouseDown, KeyDown等等,A是ViewModel中具體的函數。)

向ShellViewModel中加入事件中要做的事,此時ShellViewModel為:

using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Micro;

namespace CaliburnMicro_Calculator.ViewModels
{
    public class ShellViewModel : Screen, INotifyPropertyChanged
    {
        private double _left;
        private double _right;
        private double _result;

        public double Left
        {
            get { return _left; }
            set
            {
                _left = value;
                NotifyOfPropertyChange();
            }
        }

        public double Right
        {
            get { return _right; }
            set
            {
                _right = value;
                NotifyOfPropertyChange();
            }
        }

        public double Result
        {
            get { return _result; }
            set
            {
                _result = value;
                NotifyOfPropertyChange();
            }
        }
                public bool CanDivide(double left, double right)
        {
            return right != 0;
        }

        public async void Divide(double left, double right)
        {
            Thread.Sleep(600);
            if (CanDivide(left, right) == true)
                Result = left / right;
            else MessageBox.Show("Divider cannot be zero.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        public async void Plus(double left, double right)
        {
            Result = left + right;
        }

        public async void Minus(double left, double right)
        {
            Result = left - right;
        }

        public async void Multipy(double left, double right)
        {
            Result = left * right;
        }
    }
}
           

此時電腦的功能已基本完成,但我們可以對ViewModel進行适當的調整:

1.建立新的ViewModel - CalculatorViewModel,将原來的ShellViewModel中具體的計算邏輯移入到CalculatorViewModel中;

2.此時讓ShellViewModel繼承Conductor<Object>,于是ShellViewModel擁有了管理Screen執行個體的功能(ViewModel中使用ActivateItem函數,而View中使用X:Name="ActivateItem"标簽),其具體代碼為:

using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Micro;

namespace CaliburnMicro_Calculator.ViewModels
{
    public class ShellViewModel : Conductor<object>
    {
        public ShellViewModel()
        {
        }
        public void ShowCalculator()
        {
            ActivateItem(new CalculatorViewModel());
        }
    }
}
           

此時,CalculatorViewModel的具體代碼為:

using System.ComponentModel;
using System.Threading;
using System.Windows;
using Caliburn.Micro;

namespace CaliburnMicro_Calculator.ViewModels
{
    public class CalculatorViewModel: Screen, INotifyPropertyChanged
    {
        private double _left;
        private double _right;
        private double _result;

        public double Left
        {
            get { return _left; }
            set
            {
                _left = value;
                NotifyOfPropertyChange();
            }
        }

        public double Right
        {
            get { return _right; }
            set
            {
                _right = value;
                NotifyOfPropertyChange();
            }
        }

        public double Result
        {
            get { return _result; }
            set
            {
                _result = value;
                NotifyOfPropertyChange();
            }
        }

        public CalculatorViewModel()
        {
        }

        public bool CanDivide(double left, double right)
        {
            return right != 0;
        }

        public async void Divide(double left, double right)
        {
            Thread.Sleep(600);
            if (CanDivide(left, right) == true)
                Result = left / right;
            else MessageBox.Show("Divider cannot be zero.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        public async void Plus(double left, double right)
        {
            Result = left + right;
        }

        public async void Minus(double left, double right)
        {
            Result = left - right;
        }

        public async void Multipy(double left, double right)
        {
            Result = left * right;
        }
    }
}
           

  3 . 對于View,隻需把CalculatorViewModel對應的CalculatorView作為ContentControl控件嵌入ShellView即可。此時ShellView的代碼調整為:

<Window x:Class="CaliburnMicro_Calculator.Views.ShellView"
        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:CaliburnMicro_Calculator.Views"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="Calculator" SizeToContent="Height" Width="240">

    <Grid MinHeight="200">
        <Button Content="Show Calculator" x:Name="ShowCalculator" Grid.Row="0"></Button>
        <ContentControl x:Name="ActiveItem"></ContentControl>        
    </Grid>
</Window>
           

另外提一點,向ViewModel A中嵌入ViewModel B,一般來說需要做的操作是:

在A的view中使用ContentControl,綁定B的ViewModel隻需使用語句cal:View.Model="{Binding BViewModel}"即可,而B的view是UserControl就可以啦。

此時CalculatorView是一個UserControl,其代碼為:

<UserControl x:Class="CaliburnMicro_Calculator.Views.CalculatorView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:CaliburnMicro_Calculator.Views"
             xmlns:cal="http://www.caliburnproject.org"
             mc:Ignorable="d"
             Width="240">

    <StackPanel Background="Beige">
        <StackPanel Orientation="Horizontal">
            <Label Margin="10"
                   Target="{Binding ElementName=left}">
                Operand _1:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     x:Name="left"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Margin="10"
                   Target="{Binding ElementName=right}">
                Operand _2:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     x:Name="right"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <Button Margin="10"
                    x:Name="btnPlus" 
                    cal:Message.Attach="[Event Click]=[Action Plus(left.Text, right.Text):result.Text]">
                <Image Source="Images/op1.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnMinus" 
                    cal:Message.Attach="[Event Click]=[Action Minus(left.Text, right.Text):result.Text]">
                <Image Source="Images/op2.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnMultiply" 
                    cal:Message.Attach="[Event Click]=[Action Multipy(left.Text, right.Text):result.Text]">
                <Image Source="Images/op3.ICO"/>
            </Button>

            <Button Margin="10"
                    x:Name="btnDivide" IsEnabled="{Binding Path=CanDivide}"
                    cal:Message.Attach="[Event Click]=[Action Divide(left.Text, right.Text):result.Text]">
                <Image Source="Images/op4.ICO"/>
            </Button>

        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Margin="10">
                Answer:
            </Label>
            <TextBox Margin="10"
                     Width="72"
                     Text ="{Binding Path=Result, StringFormat={}{0:F4}, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" />
        </StackPanel>
    </StackPanel>
</UserControl>
           

好啦,就醬,由于本例中邏輯并不複雜,Model暫時用不上,對于複雜一點的項目,Model主要負責資料的讀取,如檔案操作、資料庫操作、service調用等,以後有機會舉例具體來說。

如果需要持久化(persistent),則還需給給每對M-VM(Model和ViewModel)加入State,這個實際工程中也用得特别多。

Part 6: 功能舉例

Calculator首頁:

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

點選按鈕“ShowCalculator”即可看到具體的電腦~

乘法舉例:

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

除法舉例:

從0到1:使用Caliburn.Micro(WPF和MVVM)開發簡單的電腦

最後附上代碼:

CaliburnMicro-Calculator: A simple Calculator using Caliburn.Micro

https://github.com/yanglr/CaliburnMicro-Calculator,

歡迎fork和star,如有改進意見歡迎送出pull request~

作者簡介:Bravo Yeung,計算機碩士,知乎幹貨答主(獲81K 贊同, 38K 感謝, 235K 收藏)。曾在國内 Top3網際網路視訊直播公司工作過,後加入一家外企做軟體開發至今。

如需轉載,請加微信 iMath7 申請開白!

歡迎在留言區留下你的觀點,一起讨論提高。如果今天的文章讓你有新的啟發,學習能力的提升上有新的認識,歡迎轉發分享給更多人。

歡迎各位讀者加入 .NET技術交流群,在公衆号背景回複“加群”或者“學習”即可。

文末彩蛋

微信背景回複“asp”,給你:一份全網最強的ASP.NET學習路線圖。

回複“cs”,給你:一整套 C# 和 WPF 學習資源!

回複“core”,給你:2019年dotConf大會上釋出的.NET core 3.0學習視訊!

繼續閱讀