从0到1:使用Caliburn.Micro(WPF和MVVM)开发简单的计算器 (3)

另外提一点,向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"> <StackPanel Background="Beige"> <StackPanel Orientation="Horizontal"> <Label Margin="10" Target="{Binding ElementName=left}"> Operand _1: </Label> <TextBox Margin="10" x:Name="left"/> </StackPanel> <StackPanel Orientation="Horizontal"> <Label Margin="10" Target="{Binding ElementName=right}"> Operand _2: </Label> <TextBox Margin="10" 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" Text ="{Binding Path=Result, StringFormat={}{0:F4}, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="True" /> </StackPanel> </StackPanel> </UserControl>

好啦,就酱,由于本例中逻辑并不复杂,Model暂时用不上,对于复杂一点的项目,Model主要负责数据的读取,如文件操作、数据库操作、service调用等,以后有机会举例具体来说。

如果需要持久化(persistent),则还需给给每对M-VM(Model和ViewModel)加入State,这个实际工程中也用得特别多。

Step 6: 功能举例
Calculator主页:

主页

点击按钮“ShowCalculator”即可看到具体的计算器~

乘法举例:

Multiply

除法举例:

Divide

最后附上代码:
CaliburnMicro-Calculator: A simple Calculator using Caliburn.Micro
https://github.com/yanglr/CaliburnMicro-Calculator,
欢迎fork和star,如有改进意见欢迎提交pull request~

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpyxsg.html