刚接触WPF的时候没有合适的例子进行联系,可以试试这个计算器
一、最终效果界面如下:
二、MVVM模式
View: 使用XAML呈现给用户的界面,负责与用户交互,接收用户输入,把数据展现给用户。
Model: 事物的抽象,开发过程中涉及到的事物都可以抽象为Model,例如姓名、年龄、性别、地址等属性;不包含方法,也不需要实现INotifyPropertyChanged接口.
ViewModel: 负责收集需要绑定的数据和命令,聚合Model对象,通过View类的DataContext属性绑定到View。同时也可以处理一些UI逻辑。
三、实战
1、创建WPF应用(基于.Net Framework)
布局图如上面第一张图;
界面的代码如下
<Window x:Class="WPFCalculateDemo.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:local="clr-namespace:WPFCalculateDemo"
mc:Ignorable="d"
Title="WPFCalculateDemo-By Leon"
Height="480" Width="510 "
MaxHeight="480" MinHeight="510" ResizeMode="CanMinimize"
MaxWidth="480" MinWidth="510" >
<Viewbox>
<Grid >
<TextBox Margin="19,25,236,333" FontSize="20" TextWrapping="Wrap" Text="{Binding LocalHis}"/>
<TextBox Margin="281,85,16,36" Text="{Binding History}" FontSize="10" TextWrapping="Wrap" IsReadOnly="True"/>
<TextBlock x:Name="History" Text="History:" Foreground="Black" FontSize="28" Margin="281,25,116,378"/>
<Button Content="+" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="35,230,419,201" Command="{Binding Command_CalcBtn}" CommandParameter="+"/>
<Button Content="-" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="35,285,419,146" Command="{Binding Command_CalcBtn}" CommandParameter="-"/>
<Button Content="*" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="35,340,419,91" Command="{Binding Command_CalcBtn}" CommandParameter="*"/>
<Button Content="/" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="35,395,419,36" Command="{Binding Command_CalcBtn}" CommandParameter="/"/>
<Button Content="." Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="90,395,364,36" Command="{Binding Command_CalcBtn}" CommandParameter="."/>
<Button Content="=" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="200,395,254,36" RenderTransformOrigin="4.8,-4"
Command="{Binding Command_Calculate}" CommandParameter="{Binding LocalHis}"/>
<Button Content="1" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="90,230,364,201" Command="{Binding Command_CalcBtn}" CommandParameter="1"/>
<Button Content="2" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="145,230,309,201" Command="{Binding Command_CalcBtn}" CommandParameter="2"/>
<Button Content="3" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="200,230,254,201" Command="{Binding Command_CalcBtn}" CommandParameter="3"/>
<Button Content="4" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="90,285,364,146" Command="{Binding Command_CalcBtn}" CommandParameter="4"/>
<Button Content="5" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="145,285,309,146" Command="{Binding Command_CalcBtn}" CommandParameter="5"/>
<Button Content="6" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="200,285,254,146" Command="{Binding Command_CalcBtn}" CommandParameter="6"/>
<Button Content="7" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="90,340,364,91" Command="{Binding Command_CalcBtn}" CommandParameter="7"/>
<Button Content="8" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="145,340,309,91" Command="{Binding Command_CalcBtn}" CommandParameter="8"/>
<Button Content="9" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="200,340,254,91" Command="{Binding Command_CalcBtn}" CommandParameter="9"/>
<Button Content="0" Width="50" Height="50" FontSize="40" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="145,395,309,36" Command="{Binding Command_CalcBtn}" CommandParameter="0"/>
<Button Content="CLR" Width="50" Height="50" FontSize="20" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="438,21,16,410" RenderTransformOrigin="4.8,-4"
Command="{Binding Command_ClrHis}" CommandParameter="{Binding History}"/>
<Button Content="CLR" Width="50" Height="50" FontSize="20" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="200,175,254,256" RenderTransformOrigin="4.8,-4"
Command="{Binding Command_ClrLocalHis}" CommandParameter="{Binding LocalHis}"/>
<Button Content=")" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="90,175,364,256" Command="{Binding Command_CalcBtn}" CommandParameter=")"/>
<Button Content="(" Width="50" Height="50" FontSize="30" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="35,175,419,256" Command="{Binding Command_CalcBtn}" CommandParameter="("/>
<Button Content="Bac" Width="50" Height="50" FontSize="20" Background="LightGray" HorizontalAlignment="Center"
VerticalAlignment="Center" Margin="145,175,309,256" RenderTransformOrigin="4.8,-4"
Command="{Binding Command_Back}" CommandParameter="{Binding LocalHis}"/>
</Grid>
</Viewbox>
</Window>
运行的界面和设计的界面不一致时,使用<Viewbox> </Viewbox>包含Grid,
2、在解决方案中创建Model、View以及ViewModel三个文件夹,该该实例中没有用到View的类,并在Model与ViewModel中创建对应的类,
3、CommandBase 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WPFCalculateDemo.Model
{
/// <summary>
/// 命令执行Model
/// </summary>
public class CommandBase : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
//绑定的空间可执行
return true;
}
public void Execute(object parameter)
{
DoExecute?.Invoke(parameter);
}
public Action<object> DoExecute { get; set; }
//构造函数
public CommandBase(Action<object> doExecute)
{
DoExecute = doExecute;
}
}
}
4、MainViewModel类,用作数据交互时的绑定汇总,如果有其他的Model类,都统一合并在一起,后面遇到再分享;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFCalculateDemo.Model;
namespace WPFCalculateDemo.ViewModel
{
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
#region 属性
private string history;
/// <summary>
/// 历史记录
/// </summary>
public string History
{
get { return history; }
set
{
history = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("History"));
}
}
private string localHis;
/// <summary>
/// 当前记录
/// </summary>
public string LocalHis
{
get { return localHis; }
set
{
localHis = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LocalHis"));
}
}
#endregion
#region 业务逻辑
public CommandBase Command_CalcBtn { get => new CommandBase(DoClick); }
public CommandBase Command_ClrHis { get => new CommandBase(HistoryClear); }
public CommandBase Command_ClrLocalHis { get => new CommandBase(LocalHisyClear); }
public CommandBase Command_Calculate { get => new CommandBase(Calculate); }
public CommandBase Command_Back { get => new CommandBase(GoBack); }
#endregion
#region 命令执行的逻辑
//允许继续计算
bool CalcuEnable = false;
///执行命令,点击的按钮类型进行追加
private void DoClick(object obj)
{
if (!CalcuEnable)
{
LocalHis += obj;
}
}
///退回
private void GoBack(object obj)
{
if (!CalcuEnable && LocalHis != null && LocalHis.Length > 0)
{
int length = LocalHis.Length;
LocalHis = LocalHis.Remove(length - 1, 1);
}
}
//历史记录清空
private void HistoryClear(object obj)
{
History = null;
}
//当前记录清空
private void LocalHisyClear(object obj)
{
LocalHis = null;
CalcuEnable = false;
}
//计算
private void Calculate(object obj)
{
string str = (string)obj;
if (!str.Contains("="))
{
//计算
//Calcu(LocalHis);
DataTable dt = new DataTable();
string res = dt.Compute(str, "false").ToString();
//添加等于符号及结果
DoClick("=" + res);
History += LocalHis + "\r\n";
CalcuEnable = true;
}
}
#endregion
#region 计算所需的逻辑
//private string[] GetStrArrayFromStr(string str)
//{
// return str.Split(new char[] { '+', '-', '*', '/' }, StringSplitOptions.None);
//}
#endregion
}
}
5、最后一步:将界面上的数据进行绑定,绑定好后,为界面绑定数据源
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFCalculateDemo.ViewModel;
namespace WPFCalculateDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
}
运行代码即可。
资源连接,主打一个免费分享,欢迎交流一起成长。