当前位置: 首页 > news >正文

photoshop画简单网站开发者管理

photoshop画简单网站,开发者管理,合法购物网站建设,视频网站开发前景如何〇、上位机#xff0c;分层架构 界面层 要实现的功能#xff1a; 展示数据 获取数据 发送数据 数据层 要实现的功能#xff1a; 转换数据 打包数据 存取数据 通信层 要实现的功能#xff1a; 打开连接 关闭连接 读取数据 写入数据 实体类 作用#xff1a; 封装数据…〇、上位机分层架构 界面层 要实现的功能 展示数据 获取数据 发送数据 数据层 要实现的功能 转换数据 打包数据 存取数据 通信层 要实现的功能 打开连接 关闭连接 读取数据 写入数据 实体类 作用 封装数据、传递数据 工具类 一、通信介绍及简单测试 一、PLC Programmable Logic Controller | 可编程逻辑控制器 简介 PLC的英文全称是Programmable Logic Controller中文称为“可编程逻辑控制器”。这是一种数字运算操作电子系统专为在工业环境下应用而设计。它采用可编程存储器用来在其内部存储执行逻辑运算、顺序控制、定时、计数和算术运算等操作的指令并通过数字式或模拟式的输入和输出控制各种类型的机械或生产过程。 3 1、操作西门子 smart2000 使用工具进行通讯 VD 4byte VW 2byte VB 1byte V102.0 读一1bit VB102 读1byte VW102 读2byte VD102 读4byte 二、Modbus Modbus是一种通信协议主要用于工业电子设备之间进行数据交换。 通讯的模型 1、模拟测试(TCP) 所需软件 mbpoll.exe mbslave.exe 激活码 注册码 对 7和 6 都可以使用 poll 注册码 5A5742575C5D10 slave 注册码 5455415451475662 建立 slave即服务端 poll,客户端也是类似的 进行连接 设置连接信息 收发信息的具体情况 1-2、模拟测试串口 所需软件 创建虚拟串口对 建立 主站 poll 建立从站 slave 2、存储区、存储区代码、范围 注在这里布尔和线圈是一个意思即一位的数据 注一个区的空间为 65536 每个为 2byte 大(short) 3、关于读写的功能码 4、协议分类 注ModbusASCII因为速度慢很少被使用 ModbusRTU、ModbusASCII 一般用串口 ModbusTCP 一般用以太网 5、ModbusRTU协议 举个例子 6、ModbusTCP 注Tx的最后4个字节00 00 00 0200 00 表示起始 , 而 00 02 表示读两个字节 三、串口 简介 一位一位的发送数据以协上好的频率波特率和格式 格式 9针 串口 分类 RS-232 短距离通信 RS-422 长距离通信 RS-485 折中 通常在半双工的模式下工作 RS-485标准理论上支持长达1200米的传输距离 单工 类似广播 半双工 类似对讲机 全双工 类似电话 测试虚拟串口 二、C# 通信库的使用 1、s7通信库 1、举例写一个C#与s7的通信 1、所需软件 S7-PLCSIM Advanced V.30 TIA Portal V17 VD 4byte VW 2byte VB 1byte 2、界面: 3、添加所需库 S7netplus thinger.DataConvertLib 4、代码 1.简单 测试下 连接-读写 using S7.Net; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace WindowsFormsApp1 {public partial class Form1 : Form{public Form1(){InitializeComponent();Test();}Plc plc null;private void Test(){plc new Plc(CpuType.S7200Smart, 192.168.2.1, 0, 0);plc.Open();//读取数据object data plc.Read(M20.0);this.label1.Text data.ToString();//写入数据plc.Write(M20.0, false);//不支持V区直接操作需要映射成DB1plc.Write(DB1.DBX2000.0, true);plc.Close();}} } 2.简单 的封装下 using S7.Net; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace WindowsFormsApp1 {public class S7NetLib{private Plc s7netlib null; //字段//属性public CpuType CPUType { get;set; }public string IPAddress { get; set; }public short Rack { get; set; }public short Slot { get; set; }//构造函数初始化连接 所需的变量public S7NetLib(CpuType cpuType,string ip,short rack,short slot){this.CPUType cpuType;this.IPAddress ip;this.Rack rack;this.Slot slot;}/// summary/// 打开PLC连接/// /summarypublic void OpenPLC(){if(this.s7netlib null){s7netlib new Plc(CPUType,IPAddress,Rack,Slot);}if (!this.s7netlib.IsConnected){s7netlib.ReadTimeout 1000;//设置超时时间s7netlib.WriteTimeout 1000;s7netlib.Open();//建立连接}}/// summary/// 关闭PLC连接/// /summarypublic void ClosePLC(){if(null ! this.s7netlib this.s7netlib.IsConnected){this.s7netlib.Close();}}/// summary/// 给plc单个变量写入数据/// /summary/// param namevarAddress写到那里去/param/// param namevarValue写入的值/parampublic void WriteDataToPLC(string varAddress, object varValue){OpenPLC();lock (this){this.s7netlib.Write(varAddress, varValue);}}/// summary/// 读取一段数据/// /summary/// param namedataType存储区类型/param/// param namedbDB号/param/// param namestartByteAdr开始字节地址/param/// param namecount字节数量/param/// returns字节数组/returnspublic byte[] ReadDataFromPLC(DataType dataType,int db,int startByteAdr,int count){lock (this){byte[] bytes this.s7netlib.ReadBytes(dataType,db,startByteAdr,count);return bytes;}}} } using S7.Net; using System.Windows.Forms;namespace WindowsFormsApp1 {public partial class Form1 : Form{public Form1(){InitializeComponent();Test();}private void Test(){S7NetLib plc new S7NetLib(CpuType.S7200, 192.168.2.1, 0, 0);plc.WriteDataToPLC(M2.2, true);byte[] dataBytes null;dataBytes plc.ReadDataFromPLC(DataType.DataBlock, 1, 0, 10);}} } 一次读一个PDU 的长度不同 CPU的 PDU 的长度不同 2、C# SQLSERVER 〇、环境 软件的安装服务器端、客户端 服务器端 SQL Sever 下载地址 https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 客户端 服务器端的操作 客户端的操作 两种连接方式 SQL Server 的连接配置增加使用密码登录的用户 第一步 第二步 第三步 重新启动在连接登录 . 开启远程用户登录的方式使用 IP 和 端口号 第一步 第二步 第三步重启服务 右键我的电脑点击属性 第四步最后登录 一、操作软件 SQL Server Management Studio1、两种连接方式 2、新建表 然后 ctrls 保存 3、添加数据 4、查询数据 注注释是在前面加 – 5、解决不允许保存的弹窗 6、设置主键 7、更改数据增加、删除、需改 --查select * from UserT--存--新增insert into UserT(UserName,Password,NickName) values(111,222,333)--删除delete from UserT where UserName111delete from UserT where UserName111 and Password888--修改update UserT set UserNamea where UserName111到某个指定的数据库 use QingTongXiaWaterPlant_test go修改某一段名的数据类型 use QingTongXiaWaterPlant_test go alter table dbo.WaterFlowData alter column d17 float null;二、数据库数据类型 三、数据库的约束 四、运算符 五、SQL 语句 1、搜索当前存在哪些数据库 select * from sysdatabases2、创建数据库 1、创建数据库所在的文件夹 建好的文件 2、执行 sql语句 use master go if exists(select * from sysdatabases where nameMISDB) --如果原来存在这个数据库则进行删除 drop database MISDB go --创建数据库 create database MISDB on primary (nameMISDB_MData,--必须唯一filenameD:\DB\MISDB_MData.mdf, --物理文件名主存储文件size30MB,filegrowth10MB ) , (nameMISDB_nData,filenameD:\DB\DBMISDB_nData.ndf, --次存储文件size20MB,filegrowth10MB ) log on (nameMISDB_log1,filenameD:\DB\MISDB_log1.ldf, --日志文件size20MB,filegrowth10MB ) , (nameMISDB_log2,filenameD:\DB\MISDB_log2.ldf, --日志文件size20MB,filegrowth10MB ) 3、创建表 --创建数据表是在指定的数据库里面 use MISDB go if exists(select * from sysobjects where nameDepartment) --如果已经有了 Department 表则对其进行删除 drop table Department go create table Department (DepartmentId int identity(10,1)primary key,--部门字段值由系统自动生成从10开始每次增加1 primary key 是主键的标识DepartmentName varchar(50)not null ) go if exists(select * from sysobjects where namePost) --如果已经有了 Post 表则对其进行删除 drop table Post go create table Post (PostId int identity(10,1)primary key,PostName varchar(50) not null ) go if exists(select * from sysobjects where nameEmployee) drop table Employee go create table Employee (EmplyeeId int identity(100,1) primary key,EmplyeeName varchar(50) not null,Gender char(2) not null check(Gender男 or Gender女),NowAddress nvarchar(100) default(地址不详),IdNo char(18) not null check(len(Idno)18),--检查约束WeiXinNumber varchar(20)not null,PhoneNumber varchar(50) not null,OtherWork nvarchar(50) not null,EntryDate datetime not null,PostId int references Post(PostId), --外键引用DepartmentId int references Department(DepartmentId) --外键引用 ) go4、简单的 增、删、改、查 --查select * from UserT--存--新增insert into UserT(UserName,Password,NickName) values(111,222,333)--删除delete from UserT where UserName111delete from UserT where UserName111 and Password888--修改update UserT set UserNamea where UserName111到某个指定的数据库 use QingTongXiaWaterPlant_test go修改某一段名的数据类型 use QingTongXiaWaterPlant_test go alter table dbo.WaterFlowData alter column d17 float null;5、增加 use MISDB go select * from Department select * from Post select * from Employeeinsert into Department(DepartmentName) values(开发部),(测试部),(财务部),(人事部) inSert into Post(PostName) values(软件工程师),(测试工程师),(实施工程师),(财务经理),(人事经理) insert into Employee(EmployeeName,Gender,NowAddress,IdNo, WeiXinNumber,PhoneNumber,OtherWork,EntryDate,PostId,DepartmentId)values (Kiter10,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter11,男,北京,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter12,男,福州,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter13,男,西安,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter14,男,苏州,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter15,男,咸阳,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter16,男,永寿,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter17,女,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter18,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter19,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter20,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter21,女,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter22,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter23,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter24,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter25,女,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter26,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12), (Kiter27,男,天津,123456789123456789,tt00,36954215478,没有,2024-09-09,10,12)6、删除 delete from Employee where EmployId112 delete from Employee where EmployId1177、修改 update Employee set EmployeeName小王,NowAddress天津Xwhere EmployId1018、查询及内查询 select * from Department select * from Post select * from employee--条件查询 select EmployId,EmployeeName,Gender,NowAddress,PhoneNumber from Employee where EmployId105 and EmployId115 and gender女update Employee set EmployeeName小王,NowAddress天津Xwhere EmployId101 delete from Employee where EmployId112 delete from Employee where EmployId117--内连接查询 select EmployId,EmployeeName,PhoneNumber,Post.PostId,Post.PostName from Employee inner join Post on Post.PostIdEmployee.PostId--内连接查询 select EmployId,EmployeeName,PhoneNumber, Post.PostId,PostName,DepartmentName from Employee inner join Post on Post.PostIdEmployee.PostId inner join Department on Department.DepartmentIdEmployee.DepartmentId--聚合查询 select count(*) as 员工总数 from Employee select 编号平均数avg(EmployId)from Employee select 编号最小值min(EmployId)from Employee select 编号最大值max(EmployId)from Employee9、给表增加列 ALTER TABLE Employees ADD Column1 INT,Column2 NVARCHAR(50),Column3 DATETIME; (10)、存储过程 新建 CREATE PROCEDURE JiaYao-- 输入参数 执行哪个加药Index varchar(32) ,C1_DangLiang real0,-- 输出dosage real output AS BEGIN-- 为了不返回 每条sql 影响多少条记录的信息SET NOCOUNT ON select avg(data_js_d1) as js_cod,from RealDataif IndexPAC1begin set dosage js_cod/3;endif IndexPAC2begin set dosage js_cod/2;endEND 修改 ALTER PROCEDURE JiaYao-- 输入参数 执行哪个加药Index varchar(32) ,C1_DangLiang real0,-- 输出dosage real output AS BEGIN-- 为了不返回 每条sql 影响多少条记录的信息SET NOCOUNT ON select avg(data_js_d1) as js_cod,from RealDataif IndexPAC1begin set dosage js_cod/3;endif IndexPAC2begin set dosage js_cod/2;endEND 执行的sql DECLARE dosage real;EXEC JiaYao dosage1.3,-- 输入参数 执行哪个加药Index PAC1,六、在C#中 使用SQLServer 数据库 using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Management.Instrumentation;namespace ConsoleApp1 {public class SqlServer{/** 建立连接所需要的信息* Server 是服务器的地址* DataBase 是数据库的名称* Uid 是登录的用户名* Pwd 是用户名的密码*///private string connString1 ServerE2JMKGABJ62SR4X\\SQLEXPRESS;DataBaseMISDB;Uidsa;Pwd123456;//private string connString1 Server192.168.31.130,1433\\SQLEXPRESS;DataBaseMISDB;Uidsa;Pwd123456;private string connString1 Server192.168.31.130,1433;DataBaseMISDB;Uidsa;Pwd123456;//建立连接的方法public void ConnectDB(){SqlConnection conn new SqlConnection(connString1);conn.Open();if (conn.State System.Data.ConnectionState.Open){Console.WriteLine(连接成功);}conn.Close();if (ConnectionState.Closed conn.State){Console.WriteLine(连接关闭);}}//插入语句的写法public void Insert(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//sql语句string sql insert into Employee(EmployeeName,Gender,NowAddress,IdNo,WeiXinNumber,PhoneNumber,OtherWork,EntryDate,PostId,DepartmentId)Values(Kiter30,女,天津,123456789123456789,uio001,96587112365,没有的,2024-10-06,10,12);//创建执行 sql 语句的对象SqlCommand cmd new SqlCommand(sql, conn);//连接conn.Open();//执行sql语句int result cmd.ExecuteNonQuery();//断开连接conn.Close();Console.WriteLine(受影响的行数result);}//变更数据的写法public void Update(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//sql语句string sql update Employee set EmployeeNameUBMwhere EmployId121;//创建执行 sql 语句的对象SqlCommand cmd new SqlCommand(sql, conn);//连接conn.Open();//执行sql语句int result cmd.ExecuteNonQuery();//断开连接conn.Close();Console.WriteLine(受影响的行数 result);}//删除表中的记录public void Delete(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql delete from Employee where EmployId102;//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//建立连接conn.Open();//执行 sql语句int result cmd.ExecuteNonQuery();//关闭练级conn.Close();Console.WriteLine(受影响的行数 result);}//执行查询结果为1个的 sql 语句public void GetSingleResult(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql select EmployeeName from Employee where EmployId101;//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//建立连接conn.Open();//执行 sql语句 ExecuteScalar 是执行只有一个返回结果的sql 语句object result cmd.ExecuteScalar();//关闭连接conn.Close();Console.WriteLine(result);}//执行查询结果为1个的 sql 语句public void GetSingleResult2(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql select 员工总数count(*)from Employee;//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//建立连接conn.Open();//执行 sql语句 ExecuteScalar 是执行只有一个返回结果的sql 语句object result cmd.ExecuteScalar();int count (int)result;//如果程序需要使用具体数据类型就可以转换//关闭连接conn.Close();Console.WriteLine(count);}//用 ExecuteScalar 来执行 插入操作返回看新增的记录是第几条的public void GetSingleResult3(){SqlConnection conn new SqlConnection(connString1);string sql insert into Employee(EmployeeName,Gender, NowAddress,IdNo,WeiXinNumber,PhoneNumber,OtherWork, EntryDate,PostId,DepartmentId)Values(Kiter50,男,北京,123456789123456789,qwer1,96325451784,没有,2024-11-07,10,12);sql ;select Identity;SqlCommand cmd new SqlCommand (sql,conn);conn.Open();int result Convert.ToInt32(cmd.ExecuteScalar());conn.Close();Console.WriteLine(编号result);}//读取多条记录 (查询的 多个表)public void GetReaderList(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql select EmployeeName,Gender,NowAddress from Employee;//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//建立连接conn.Open();//执行结果集查询SqlDataReader reader cmd.ExecuteReader();//逐行读取while (reader.Read()){string result reader[EmployeeName].ToString() reader[Gender] reader[NowAddress];Console.WriteLine(result);}//释放资源reader.Close(); //关闭读取器conn.Close(); //关闭连接}//读取多条记录查询的是多个表public void GetReaderList2(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql select EmployeeName,Gender,NowAddress from Employee;sql ;select DepartmentId,DepartmentName from Department;//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//建立连接conn.Open();//执行结果集查询SqlDataReader reader cmd.ExecuteReader();//逐行读取while (reader.Read()){string result reader[EmployeeName].ToString()\treader[1]\treader[NowAddress];Console.WriteLine(result);}Console.WriteLine(*************);if (reader.NextResult()){while (reader.Read()){Console.WriteLine(${reader[DepartmentId]}\t{reader[DepartmentName]});}}//关闭读取器reader.Close();//关闭连接conn.Close();}//使用 DataSet 和 SqlDataAdapter 读取多条记录public void GetDataSet1(){//创建连接对象SqlConnection conn new SqlConnection(connString1);//sql 语句string sql select EmployeeName,Gender,NowAddress from Employee;//创建执行sql的对象SqlCommand cmd new SqlCommand(sql, conn);//打开连接conn.Open();//创建数据适配器对象SqlDataAdapter da new SqlDataAdapter(cmd);//创建一个数据集对象DataSet ds new DataSet();//将查询到到结果填入到内存中DataSetda.Fill(ds);//关闭连接conn.Close();//读取数据DataTable dt ds.Tables[0];foreach(DataRow dr in dt.Rows){Console.WriteLine(${dr[EmployeeName]}\t{dr[Gender]}\t{dr[NowAddress]});}}//使用 DataSet 和 SqlDataAdapter 读取多条记录查询的是多个表public void GetDataSet2(){//创建连接对象SqlConnection conn new SqlConnection(connString1);//sql 语句string sql select EmployeeName,Gender,NowAddress from Employee;//创建执行sql的对象SqlCommand cmd new SqlCommand(sql, conn);//打开连接conn.Open();//创建数据适配器对象SqlDataAdapter da new SqlDataAdapter(cmd);//创建一个数据集对象DataSet ds new DataSet();//填充数据da.Fill(ds,Employee);cmd.CommandText select DepartmentId,DepartmentName from Department;da.Fill(ds, Department);//关闭连接conn.Close();//读取数据DataTable dt ds.Tables[Employee];foreach(DataRow dr in dt.Rows){Console.WriteLine(${dr[EmployeeName]}\t{dr[Gender]}\t{dr[NowAddress]});}Console.WriteLine(........................);foreach(DataRow dr in ds.Tables[Department].Rows){Console.WriteLine(${dr[DepartmentId]}\t{dr[DepartmentName]});}}//写带 参数的SQL 语句public void GetReaderList5(){//创建建立连接的对象 -- SqlConnectionSqlConnection conn new SqlConnection(connString1);//要执行的 sql 语句string sql select EmployeeName,Gender,NowAddress from Employee where EmployId Number;SqlParameter[] param new SqlParameter[]{new SqlParameter(Number,106)};//实例化 要执行 sql的对象 -- SqlCommandSqlCommand cmd new SqlCommand(sql, conn);//添加参数cmd.Parameters.AddRange(param);//建立连接conn.Open();//执行结果集查询SqlDataReader reader cmd.ExecuteReader();//逐行读取while (reader.Read()){string result reader[EmployeeName].ToString() \t reader[1] \t reader[NowAddress];Console.WriteLine(result);}//关闭读取器reader.Close();//关闭连接conn.Close();}} } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApp1 {internal class Program{static void Main(string[] args){SqlServer sqlServer new SqlServer();//建立连接然后断开//sqlServer.ConnectDB();//插入新的行//sqlServer.Insert();//修改数据库中的信息//sqlServer.Update();//删除数据库中的记录//sqlServer.Delete();//执行只返回一个结果的 sql 语句//sqlServer.GetSingleResult();//执行只返回一个结果的 sql 语句//sqlServer.GetSingleResult2();//用 ExecuteScalar 来执行 插入操作返回看新增的记录是第几条的//sqlServer.GetSingleResult3();//读取多条记录//sqlServer.GetReaderList();//读取多个表的多条记录//sqlServer.GetReaderList2();//使用 SqlDataAdapter 和 DataSet 读取数据//sqlServer.GetDataSet1();//使用 SqlDataAdapter 和 DataSet 读取多个表的数据//sqlServer.GetDataSet2();//使用带参的sql语句sqlServer.GetReaderList5();Console.ReadLine();}} }查询 通过关闭 SqlDataReader来关闭 SqlConnection 七、SqlHelper 先安装库 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Web; //using System.Data.SqlClient; using System.Data; using Microsoft.SqlServer.Server;using Microsoft.Data.SqlClient; using System.Configuration;namespace ToolsLib {public class SqlServerHelper{//用于连接数据库的字符串//private static string ConnString { get; set; } ConfigurationManager.ConnectionStrings[connString1].ToString();private static string ConnString { get; set; } ConfigurationManager.AppSettings[connString1];/// summary/// 执行 insert\update\delete 类型的 sql 语句/// /summary/// param namecmdTextsql语句或存储过程名称/param/// param nameparamArray参数数组/param/// returns受影响的行数/returns/// exception crefException/exceptionpublic static int ExecuteNonQuery(string cmdText, SqlParameter[] paramArray null){SqlConnection conn new SqlConnection(ConnString);SqlCommand cmd new SqlCommand(cmdText, conn);if (paramArray ! null){cmd.Parameters.AddRange(paramArray);}try{conn.Open();return cmd.ExecuteNonQuery();//执行}catch (Exception ex){//可以在这个地方写入日志log文件string errorMsg ${DateTime.Now}:执行public static int ExecuteNonQuery(sting cmdText,SqlParameter[]para---{ex.Message};throw new Exception(errorMsg);}finally{conn.Close();}}/// summary/// 执行查询语句查询结果是但是一个结果/// /summary/// param namecmdText/param/// param nameparamArray/param/// returns/returns/// exception crefException/exceptionpublic static object ExecuteScalar(string cmdText, SqlParameter[] paramArray null){SqlConnection conn new SqlConnection(ConnString);SqlCommand cmd new SqlCommand(cmdText, conn);if (paramArray ! null){cmd.Parameters.AddRange(paramArray);}try{conn.Open();return cmd.ExecuteScalar();}catch (Exception ex){throw new Exception(执行public staticobjectExecute Scalarstring cmdText,SqlParameter[] paramArray null)异常 ex.Message);}finally{conn.Close();//关闭连接}}/// summary/// 执行查询语句/// /summary/// param namecmdText/param/// param nameparamArray/param/// returns/returns/// exception crefException/exceptionpublic static SqlDataReader ExecuteReader(string cmdText, SqlParameter[] paramArray null){SqlConnection conn new SqlConnection(ConnString);SqlCommand cmd new SqlCommand(cmdText, conn);if (paramArray ! null){cmd.Parameters.AddRange(paramArray);}try{conn.Open();//这里返回的 SqlDataReader 是用来进行进一步查询的//这里的 加的入参是CommandBehavior.CloseConnection 为了关闭 SqlDataReader后来自动关闭 conn连接 做设置//因为 SqlDataReader 是需要在外部进行访问的return cmd.ExecuteReader(CommandBehavior.CloseConnection);//执行}catch (Exception ex){throw new Exception($执行public staticobjectExecute ScalarstringcmdText,SqlParameter[] paramArraynull) ---{ex.Message});}}/// summary/// 返回包含一张数据表的数据集的查询/// /summary/// param namesql/param/// param nametableName/param/// returns/returns/// exception crefException/exceptionpublic static DataSet GetDataSet(string sql, string tableName null){SqlConnection conn new SqlConnection(ConnString);SqlCommand cmd new SqlCommand(sql, conn);SqlDataAdapter da new SqlDataAdapter(cmd);DataSet ds new DataSet();try{conn.Open();if (tableName null){da.Fill(ds);}else{da.Fill(ds, tableName);}return ds;}catch (Exception ex){throw new Exception($执行public static DataSet GetDataSet(string sql,string tableNamenull)方法出现异常{ex.Message});}finally{conn.Close();}}public static DataSet GetDataSet(Dictionarystring, string dicTableAndSql){SqlConnection conn new SqlConnection(ConnString);SqlCommand cmd new SqlCommand();cmd.Connection conn;SqlDataAdapter da new SqlDataAdapter(cmd);DataSet ds new DataSet();try{conn.Open();foreach (string tbName in dicTableAndSql.Keys){cmd.CommandText dicTableAndSql[tbName];da.Fill(ds, tbName);//加入多个表}return ds;}catch (Exception ex){throw new Exception(执行public static DataSet GetDataSet(string ssql,string tableNamenull)方法出行异常 ex.Message);}finally{conn.Close();}}} } 八、存储过程的写法 创建 SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GOCREATE PROCEDURE TestProcedureParameter1 Int 0,Parameter2 Int output AS BEGINSET NOCOUNT ONselect * from UserT;Set Parameter2 999; END GO修改 USE [MyDB] GO /****** Object: StoredProcedure [dbo].[TestProcedure] Script Date: 12/17/2024 10:08:29 AM ******/ -- 与null比较的结果会被视为 未知而不是 true 或 false SET ANSI_NULLS ON GO -- 可以使用用双引号引起来的关键字 SET QUOTED_IDENTIFIER ON GOALTER PROCEDURE [dbo].[TestProcedure]-- 输入参数Parameter1 Int 0,-- 输出参数Parameter2 Int output AS BEGIN-- 为了不返回 每条sql 影响多少条记录的信息SET NOCOUNT ONselect * from UserT;Set Parameter2 999; END执行 declare Parameter2 int;exec TestProcedure Parameter120, Parameter2 Parameter2 output;select Parameter2 as Parameter2;3、NModbus4 通讯库的使用 1、使用串口封装 NModbus4 库 安装 NModbus4 库 封装的代码 using Modbus.Device; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks;namespace WindowsFormsApp1 {/// summary/// 基于NModbus4的开源库的二次封装/// /summaryinternal class ModbusRTU{#region 串口打开//声明.NET串口对象private SerialPort serialPort;//声明Modbus协议串口主设备对象private ModbusSerialMaster master;// COM1 9600 N 8 1 public bool Connect(string portName, int baudRate,Parity parity,int dataBits,StopBits stopBits){if(this.serialPort null this.serialPort.IsOpen){this.serialPort.Close();}try{//创建.NET串口对象this.serialPort new SerialPort(portName,baudRate, parity,dataBits,stopBits);//设置串口的读写超时时间防止长时间阻塞this.serialPort.ReadTimeout 1000;this.serialPort.WriteTimeout 1000;//打开 .NET 串口this.serialPort.Open();//使用 Modbus串口工厂方法 创建 Modbus串口主设备 对象master ModbusSerialMaster.CreateRtu(this.serialPort);return true;}catch(Exception ex){//打印异常信息throw new Exception([串口]打开失败ex.Message);}}#endregion#region 关闭串口public void DisConnect(){if(this.serialPort ! null this.serialPort.IsOpen){//this.serialPort?.Close();this.serialPort.Close();}master null;}#endregion#region 读取数据/// summary/// 【01】功能码读取输出线圈/// /summary/// param nameslaveId从站地址/param/// param namestart起始线圈地址/param/// param namelength线圈的数量/param/// returns返回bool数组/returns/// exception crefException/exceptionpublic bool[]ReadOutputCoils(byte slaveId,ushort start,ushort length){try{//Coils 线圈的意思return this.master.ReadCoils(slaveId, start, length);}catch(Exception ex){throw new Exception([读取输出线程]失败 ex.Message);}}/// summary/// [02] 功能码读取输入线圈/// /summary/// param nameslaveId从站地址/param/// param namestart起始线圈地址/param/// param namelength线圈的数量/param/// returns返回bool数组/returns/// exception crefException/exceptionpublic bool[] ReadInputCoils(byte slaveId, ushort start, ushort length){try{return this.master.ReadInputs(slaveId, start, length);}catch (Exception ex){throw new Exception([读取输入线圈]失败: ex.Message);}}// 一个寄存器是两个 字节的大小/// summary/// 【03】 功能码读取输出寄存器/// /summary/// param nameslaveId从站地址/param/// param namestart起始寄存器地址/param/// param namelength寄存器的数量/param/// returns返回byte数组/returns/// exception crefException/exceptionpublic byte[] ReadHoldingRegister(byte slaveId,ushort start,ushort length){try{//获取数据数组ushort[] data this.master.ReadHoldingRegisters(slaveId, start, length);// 一个寄存器是两个 字节的大小//把ushort类型数组转换成List字节数组Listbyte result new Listbyte();foreach(var item in data){result.AddRange(BitConverter.GetBytes(item));}return result.ToArray();}catch(Exception ex){throw new Exception([读取输出寄存器]失败 ex.Message);}}/// summary/// [04] 功能码读取输入寄存器/// /summary/// param nameslaveId从站地址/param/// param namestart起始寄存器地址/param/// param namelength寄存器的数量/param/// returns返回byte数组/returns/// exception crefException/exceptionpublic byte[] ReadInputRegister(byte slaveId,ushort start,ushort length){try{//获取数据数组ushort[] data this.master.ReadInputRegisters(slaveId, start, length);//把ushort类型的数组转换成List字节数组Listbyte result new Listbyte();foreach (var item in data){result.AddRange(BitConverter.GetBytes(item));}return result.ToArray();}catch(Exception ex){throw new Exception([读取输入寄存器]失败 ex.Message);}}#endregion#region 写入数据/// summary/// [05] 功能码预置单线圈/// /summary/// param nameslaveId从站地址/param/// param namestart当前线圈地址/param/// param namevalue线圈的值/param/// returns/returns/// exception crefException/exceptionpublic bool PreSetSingleCoil(byte slaveId,ushort start,bool value){try{this.master.WriteSingleCoil(slaveId, start, value);return true;}catch(Exception ex){throw new Exception([预置单线圈]失败 ex.Message);}}/// summary/// [06]功能码预置单寄存器/// /summary/// param nameslaveId从站地址/param/// param nameaddress寄存器地址/param/// param namevalue字节地址2个字节/param/// returns/returns/// exception crefException/exceptionpublic bool PreSetSingleRegister(byte slaveId,ushort address,byte[] value){try{this.master.WriteSingleRegister(slaveId, address, BitConverter.ToUInt16(value, 0));return true;}catch (Exception ex){throw new Exception(【预置单寄存器】失败 ex.Message);}}public bool PreSetSingleRegister(byte slaveId,ushort address,short value){return PreSetSingleRegister(slaveId, address, BitConverter.GetBytes(value));}public bool PreSetSingleRegister(byte slaveId,ushort address,ushort value){return PreSetSingleRegister(slaveId, address, BitConverter.GetBytes(value));}/// summary/// 【0F】 功能码 预置多个线圈/// /summary/// param nameslaveId从站地址/param/// param namestart线圈开始地址/param/// param namevalue布尔数组/param/// returns/returns/// exception crefException/exceptionpublic bool PreSetMutiCoils(byte slaveId,ushort start,bool[] value){try{this.master.WriteMultipleCoils(slaveId, start, value);return true;}catch(Exception ex){throw new Exception([预制多线圈]失败 ex.Message);}}/// summary/// [10] 功能码预制多个寄存器/// /summary/// param nameslaveId从站地址/param/// param namestart寄存器开始地址/param/// param namevalues字节数组/param/// returns/returns/// exception crefException/exceptionpublic bool PreSetMultiRegister(byte slaveId,ushort start, byte[] values){//必须是偶数字节// 因为两字节 才是也给寄存器的大小if(values null||values.Length 0 || values.Length%2 1){return false;}//将字节数组转换成ushort数组ushort[] data new ushort[values.Length / 2];for (int i 0; i values.Length; i 2){data[i] BitConverter.ToUInt16(values, i);}try{this.master.WriteMultipleRegisters(slaveId, start, data);return true;}catch(Exception ex){throw new Exception([预制多寄存器]失败ex.Message);}}/// summary/// [0F] 功能码预制多个线圈/// /summary/// param nameslaveId站地址/param/// param namestart线圈开始地址/param/// param namevalue布尔数组/param/// returns/returns/// exception crefException/exceptionpublic bool PreSetMultiCoils(byte slaveId,ushort start,bool[] value){try{this.master.WriteMultipleCoils(slaveId,start,value);return true;}catch (Exception ex) {throw new Exception([预制多个线圈]失败 ex.Message);}}#endregion} } 三、手写通信库 四、WPF基本使用 0、xaml 的基础操作 xaml是一种声明型语言一般来讲一个标签就是一个对象而一个标签的属性就是一个对象的属性。 给标签属性赋值有三种方式 1、 Attribute Value 形式 画一个 长方形 Rectangle Width100 Height80 StrokeBlack/画一个三角形 Path DataM 0,0 L 200,100 L 100,200 Z StrokeBlack FillRed/将一个字符串转换成标签对象的写法 MainWindow.xaml Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitleMainWindow Height450 Width800Window.Resourceslocal:Dog x:Keydog1 NameBob1/local:Dog x:Keydog2 NameBob2/local:Dog x:Keydog3 NameBob3 Child123//Window.ResourcesGridButton ContentHello! Width120 Height30 ClickButton_Click//Grid /WindowDog.cs using System.ComponentModel; using System.Globalization;namespace WpfApp1 {//为类添加转换规则[TypeConverterAttribute(typeof(NameToDogTypeConverter))]public class Dog{public string Name { get; set; }public Dog Child { get; set; }}public class NameToDogTypeConverter : TypeConverter{//将字符串转成 Dog 的规则public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value){string name value.ToString();Dog child new Dog();child.Name name;return child;}} } MainWindow.xaml.cs using System.Windows;namespace WpfApp1 {/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private void Button_Click(object sender, RoutedEventArgs e){Dog dog this.FindResource(dog3) as Dog; ;//找到字典资源中 标签对象的方法if(null ! dog){//取出标签对象中的属性MessageBox.Show(dog.Name / dog.Child.Name);}}} }另一种等价的添加属性 的方式 Button Content登录 FontSize20 Height50 Width300/Button Content登录Setter PropertyBackground ValueRed/Setter PropertyFontSize Value20/Setter PropertyHeight Value50/Setter PropertyWidth Value300//Button2、属性标签 形如 LinearGradientBrush.StartPoint 就是属性标签它不是一个对象而是对象的属性用标签的形式来写 例子 1: Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006mc:IgnorabledTitleMainWindow Height450 Width800GridRectangle Width200 Height160 StrokeBlueRectangle.FillLinearGradientBrushLinearGradientBrush.StartPointPoint X0 Y0//LinearGradientBrush.StartPointLinearGradientBrush.EndPointPoint X1 Y1//LinearGradientBrush.EndPointLinearGradientBrush.GradientStopsGradientStopCollectionGradientStop Offset0.2 ColorLightBlue/GradientStop Offset0.7 ColorDarkBlue/GradientStop Offset1.0 ColorBlue//GradientStopCollection/LinearGradientBrush.GradientStops/LinearGradientBrush/Rectangle.Fill/Rectangle/Grid /Window 例子 2: Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006mc:IgnorabledTitleMainWindow Height450 Width800GridButton Width120 Height30Button.ContentRectangle Width20 Height20 StrokeDarkGreen FillLawnGreen//Button.Content/Button/Grid /Window 3、标签扩展 1、创建一个项目 程序入口 默认入口点WPF 应用程序的默认入口点是 App.xaml 和 App.xaml.cs 文件。在这些文件中定义了应用程序的启动逻辑和主窗口。 自定义入口点如果需要可以在代码中定义一个 Main 方法并在其中创建和运行 Application 对象但这不是必需的除非你有特定的初始化需求。 手写函数函数入口一般不需要 // Entry point defined in a custom Main method (if needed) public static class Program {[STAThread]public static void Main(){var app new App();app.InitializeComponent();app.Run();} }// App.xaml.cs using System.Windows;namespace MyWpfApp {public partial class App : Application{// Application startup logic can be placed hereprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Custom startup logic (if needed)}protected override void OnExit(ExitEventArgs e){base.OnExit(e);// Custom exit logic (if needed)}} } 窗体 xaml 文件的解读 2、模拟一个文本编辑的界面使用控件Grid | StackPanel | Button | TextBox 准备 button的属性 Width HorizontalAlignment VerticalAlignment Height GridButton Width200 HorizontalAlignmentLeft VerticalAlignmentTop Height40/Button Width200 HorizontalAlignmentCenter VerticalAlignmentTop Height40/Button Width200 HorizontalAlignmentRight VerticalAlignmentTop Height40/Button Width200 HorizontalAlignmentLeft VerticalAlignmentCenter Height40/Button Width200 HorizontalAlignmentCenter VerticalAlignmentCenter Height40/Button Width200 HorizontalAlignmentRight VerticalAlignmentCenter Height40/Button Width200 HorizontalAlignmentLeft VerticalAlignmentBottom Height40/Button Width200 HorizontalAlignmentCenter VerticalAlignmentBottom Height40/Button Width200 HorizontalAlignmentRight VerticalAlignmentBottom Height40//GridStackanel控件 . 占用多列的写法 Grid.ColumnSpan“2” StackPanel OrientationVertical HorizontalAlignmentCenterButton Height20 Width70/Button Height20 Width70/Button Height20 Width70//StackPanelStackPanel OrientationHorizontal HorizontalAlignmentCenterButton Height20 Width70/Button Height20 Width70/Button Height20 Width70//StackPanelGrid控件 Grid ShowGridLinesTrueGrid.RowDefinitionsRowDefinition Height1*/RowDefinition Height1*/RowDefinition Height1*/RowDefinition Height1*//Grid.RowDefinitionsGrid.ColumnDefinitionsColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*//Grid.ColumnDefinitionsButton Grid.Row1 Grid.Column11,1/ButtonButton Grid.Row1 Grid.Column21,2/ButtonButton Grid.Row1 Grid.Column31,3/ButtonButton Grid.Row2 Grid.Column12,1/ButtonButton Grid.Row2 Grid.Column22,2/ButtonButton Grid.Row2 Grid.Column32,3/Button/GridGrid 的三种长度设置 AUTO 安内容来 绝对宽高 每个单位是 1/96英寸 “1*” 按比例来 TextBox 文本编辑的控件 TextBox TextWrappingWrap/应用 Window x:ClassWpfApp1.EditWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitleEditWindow Height450 Width800GridGrid.RowDefinitionsRowDefinition Height20/RowDefinition Height20/RowDefinition Height1*/RowDefinition Height20//Grid.RowDefinitionsStackPanel Grid.Row0 Grid.Column0 OrientationHorizontalButton Height20 Width70 Content文件/Button Height20 Width70 Content编辑/Button Height20 Width70 Content查看/Button Height20 Width70 Content外观/Button Height20 Width70 Content设置//StackPanelStackPanel Grid.Row1 Grid.Column0 OrientationHorizontalButton Height20 Width20 Content1/Button Height20 Width20 Content2/Button Height20 Width20 Content3/Button Height20 Width20 Content4/Button Height20 Width20 Content5//StackPanelGrid Grid.Row2 Grid.Column0GridGrid.ColumnDefinitionsColumnDefinition Width40/ColumnDefinition//Grid.ColumnDefinitionsStackPanel Grid.Column0 Grid.Row0Button Height20 Content1/Button Height20 Content2/Button Height20 Content3/Button Height20 Content4/Button Height20 Content5/Button Height20 Content6/Button Height20 Content7/Button Height20 Content8/Button Height20 Content9/Button Height20 Content10/Button Height20 Content11/Button Height20 Content12/Button Height20 Content13/Button Height20 Content14/Button Height20 Content15/Button Height20 Content16/Button Height20 Content17//StackPanelTextBox Grid.Column1 TextWrappingWrap//Grid/GridGrid Grid.Row3 Grid.Column0Grid.ColumnDefinitionsColumnDefinition Widthauto/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*/ColumnDefinition Width1*//Grid.ColumnDefinitionsButton Grid.Column0Normal text file/ButtonButton Grid.Column1Length:1,125/ButtonButton Grid.Column2lines:26/ButtonButton Grid.Column3Ln:6 Col:57 Sel:3/ButtonButton Grid.Column41/ButtonButton Grid.Column5Windows(CR LF)/ButtonButton Grid.Column6UTF-8-BOM/ButtonButton Grid.Column7INS/Button/Grid/Grid /Window2-2 布局器的使用 1、StackPanel 水平或垂直排列元素、Orientation 属性分别为Horizontal / Verical 2、WrapPanel 水平或垂直排列元素、剩余控件不足会进行换行、换列的排布 3、DockPanel 根据容器的边界、元素进行 Dock.Top 、Left 、Right 、Bottom 4、Grid 类似 table表格 5、UniformGrid 指定行和列的数量均匀有限的容器空间 6、Canvas 使用固定的坐标设置元素的位置 3、样式 样式写在 Window.Resources 里的 Style 里 //定义 在标签里加属性Style Style“{StaticResource LoginStyle}” //使用 StaticResource 静态加载 DynamicResource 动态加载在运行的时候改变 xaml 文件内容样式是会发生改变的 Window x:ClassWpfApp1.EditWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitleEditWindow Height450 Width800Window.ResourcesStyle TargetTypeButtonSetter PropertyBackground ValueWhiteSmoke/Setter PropertyFontSize Value20/Setter PropertyHeight Value50/Setter PropertyWidth Value300/Setter PropertyMargin Value20,10//StyleStyle x:KeyLoginStyle TargetTypeButtonSetter PropertyBackground ValueGreen/Setter PropertyFontSize Value20/Setter PropertyHeight Value50/Setter PropertyWidth Value300//StyleStyle x:KeyQuitStyle TargetTypeButton BasedOn{StaticResource {x:Type Button} }Setter PropertyBackground ValueRed//Style/Window.ResourcesStackPanelButton Style{StaticResource LoginStyle} Content登录/Button Style{DynamicResource QuitStyle} Content退出/Button Content忘记密码//StackPanel/Window继承 Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlTitle登录界面 Height270 Width500 ResizeModeNoResizeWindow.ResourcesStyle x:KeybaseButtonStyle TargetTypeButtonSetter PropertyFontSize Value30/Setter PropertyForeground ValueBlue//StyleStyle x:KeydefaultButtonStyle TargetTypeButton BasedOn{StaticResource baseButtonStyle}Setter PropertyWidth Value100/Setter PropertyHeight Value50//Style/Window.ResourcesGridButton Style{StaticResource defaultButtonStyle} Contentghyu//Grid /Window4、添加资源字典 第一步添加资源字典 xaml 文件 资源字典文件Dictionary1.xaml ResourceDictionary xmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlStyle TargetTypeButtonSetter PropertyBackground ValueWhiteSmoke/Setter PropertyFontSize Value20/Setter PropertyHeight Value50/Setter PropertyWidth Value300/Setter PropertyMargin Value20,10//StyleStyle x:KeyLoginStyle TargetTypeButtonSetter PropertyBackground ValueGreen/Setter PropertyFontSize Value20/Setter PropertyHeight Value50/Setter PropertyWidth Value300//StyleStyle x:KeyQuitStyle TargetTypeButton BasedOn{StaticResource {x:Type Button} }Setter PropertyBackground ValueRed//Style /ResourceDictionary第二步在 app.xml 文件中引入 资源字典文件 ResourceDictionary Source/WpfApp1;component/Dictionary1.xaml/这里的 WpfApp1 是 命名空间Dictionary1.xaml 是 要加载的文件名Application x:ClassWpfApp1.Appxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:localclr-namespace:WpfApp1StartupUriEditWindow.xamlApplication.ResourcesResourceDictionaryResourceDictionary.MergedDictionariesResourceDictionary Source/WpfApp1;component/Dictionary1.xaml//ResourceDictionary.MergedDictionaries/ResourceDictionary/Application.Resources /Application第三步在标签中可以直接调用 Window x:ClassWpfApp1.EditWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitleEditWindow Height450 Width800StackPanelButton Style{StaticResource LoginStyle} Content登录/Button Style{DynamicResource QuitStyle} Content退出/Button Content忘记密码//StackPanel /Window5、用模板自定义一个带圆角的 Button 控件 及 触发器 的写法 ControlTemplate TargetTypeButton里 TargetType“Button” 和 TargetTye“{x:Type Button}” 是一样的 Border Background{TemplateBinding Background} BorderBrush{TemplateBinding BorderBrush} BorderThickness{TemplateBinding BorderThickness} CornerRadius6在这一行中{TemplateBinding Background} 表示从原 button 标签中去取 叫 Background 的属性 Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitle123 Height450 Width800GridButton Contentbtn BackgroundRed BorderBrushBlack FontSize20 Width200 Height30 BorderThickness3Button.TemplateControlTemplate TargetTypeButtonBorder x:Nameboder Background{TemplateBinding Background} BorderBrush{TemplateBinding BorderBrush} BorderThickness{TemplateBinding BorderThickness} CornerRadius6TextBlock Text{TemplateBinding Content} HorizontalAlignmentCenter VerticalAlignmentCenter//BorderControlTemplate.TriggersTrigger PropertyIsMouseOver ValueTrueSetter TargetNameboder PropertyBackground ValueBlack//TriggerTrigger PropertyIsPressed ValueTrueSetter TargetNameboder PropertyBackground ValueWhiteSmoke//Trigger/ControlTemplate.Triggers/ControlTemplate/Button.Template/Button/Grid /Window 解读 Grid: 一个布局容器用于布局子元素。在这个例子中它包含了一个 Button 控件。 Button: 一个按钮控件具有以下属性 Content“btn”: 按钮的显示文本为 “btn”。 Background“Red”: 按钮的背景颜色为红色。 BorderBrush“Black”: 按钮的边框颜色为黑色。 FontSize“20”: 按钮文本的字体大小为 20。 Width“200”: 按钮的宽度为 200 像素。 Height“30”: 按钮的高度为 30 像素。 BorderThickness“3”: 按钮的边框厚度为 3 像素。 ControlTemplate: 定义了 Button 控件的外观模板。TargetType“Button” 指定这个模板用于 Button 控件。 Border: 包含了按钮的主要视觉部分。 x:Name“boder”: 给 Border 起了一个名字 boder以便在触发器中引用。 Background“{TemplateBinding Background}”: Border 的背景颜色绑定到按钮的 Background 属性。 BorderBrush“{TemplateBinding BorderBrush}”: Border 的边框颜色绑定到按钮的 BorderBrush 属性。 BorderThickness“{TemplateBinding BorderThickness}”: Border 的边框厚度绑定到按钮的 BorderThickness 属性。 CornerRadius“6”: Border 的圆角半径设置为 6 像素使边角有一定的圆润效果。 TextBlock: 显示按钮的文本内容。 Text“{TemplateBinding Content}”: TextBlock 的文本绑定到按钮的 Content 属性。 HorizontalAlignment“Center”: 文本在水平方向居中对齐。 VerticalAlignment“Center”: 文本在垂直方向居中对齐. 5-2、触发器 的另一些实践 Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlTitle登录界面 Height270 Width500Window.ResourcesStyle x:KeydefaultButtonStyle TargetTypeButtonSetter PropertyWidth Value100/Setter PropertyHeight Value30/Style.TriggersTrigger PropertyIsMouseOver ValueTrueSetter PropertyForeground ValueRed/Setter PropertyFontSize Value30//TriggerTrigger PropertyIsMouseOver ValueFalseSetter PropertyForeground ValueBlue/Setter PropertyFontSize Value20//Trigger/Style.Triggers/StyleStyle x:KeydefaultButtonStyle2 TargetTypeButtonSetter PropertyWidth Value100/Setter PropertyHeight Value30/Style.TriggersMultiTriggerMultiTrigger.ConditionsCondition PropertyIsMouseOver Valuetrue/Condition PropertyIsFocused ValueTrue//MultiTrigger.ConditionsMultiTrigger.SettersSetter PropertyForeground ValueRed//MultiTrigger.Setters/MultiTrigger/Style.Triggers/StyleStyle x:KeydefaultButtonStyle3 TargetTypeButtonSetter PropertyWidth Value100/Setter PropertyHeight Value30/Style.TriggersEventTrigger RoutedEventMouse.MouseEnterEventTrigger.ActionsBeginStoryboardStoryboardDoubleAnimation Duration0:0:0.2Storyboard.TargetPropertyFontSizeTo30/DoubleAnimation/Storyboard/BeginStoryboard/EventTrigger.Actions/EventTrigger/Style.Triggers/Style/Window.ResourcesStackPanelButton Style{StaticResource defaultButtonStyle} ContentHello/Button Style{StaticResource defaultButtonStyle2} ContentHello/Button Style{StaticResource defaultButtonStyle3} ContentHello//StackPanel /Window 5-3、生成模板副本 将 模板放在 资源字典中 5-4、控件模板 5-5、数据模板 第一个例子 第二个例子 6、 button 的 和 点击事件 的写法 6-2、添加点击事件的两种方式 1 直接在 xaml 代码中进行添加 2 根据名字找到控件的 点击事件在 cs 代码中添加 Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:sysclr-namespace:System;assemblymscorlibTitleMainWindow Height450 Width800Window.Resourcessys:String x:KeystringHelloHello WPF!/sys:String/Window.ResourcesGridTextBlock Height24 Width120 BackgroundLightBlueText{StaticResource ResourceKeystringHello}//Grid /Window7-1、控件间的属性绑定 GridStackPanelSlider x:Nameslider Margin5/TextBoxHeight30Margin5Text{Binding ElementNameslider, PathValue, ModeOneTime}/!--只进行一次绑定--TextBoxHeight30Margin5Text{Binding ElementNameslider, PathValue, ModeOneWay}/!--单向绑定--TextBoxHeight30Margin5Text{Binding ElementNameslider, PathValue}/!--默认是双向绑定--/StackPanel/Grid7-2、一个简单的数据绑定的写法(属性的变更通知) 完成前 3 步可以实现 数据从界面 向 代码的传递 完成后 2 步可以实现 界面 向 代码层的数据传递 代码 Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfApp1mc:IgnorabledTitle登录界面 Height270 Width500 ResizeModeNoResizeGridGrid.RowDefinitionsRowDefinition Height15/RowDefinition Height30/RowDefinition Heightauto/RowDefinition Height5*//Grid.RowDefinitionsTextBox Grid.Row1 TextX6337TEB6----登录系统 HorizontalAlignmentCenter VerticalAlignmentCenter FontSize16/Grid Grid.Row2Grid.RowDefinitionsRowDefinition Height20/RowDefinition Height20/RowDefinition Height20/RowDefinition Height27//Grid.RowDefinitionsGrid.ColumnDefinitionsColumnDefinition Width1*/ColumnDefinition Widthauto/ColumnDefinition Width150/ColumnDefinition Width1*//Grid.ColumnDefinitionsTextBlock Grid.Row0 Grid.Column1 Text用户名/TextBox Text {Binding UserName} Grid.Row0 Grid.Column2 Margin3,2/TextBlock Grid.Row1 Grid.Column1 Text密码/TextBox Text{Binding PassWord} Grid.Row1 Grid.Column2 Margin3,2/CheckBox Grid.ColumnSpan2 Grid.Row2 Grid.Column1 Content记住密码/Button Grid.ColumnSpan2 Grid.Row3 Grid.Column1 Content登录 Margin3,1 ClickButton_Click//Grid/Grid /Window using System; using System.ComponentModel; using System.Windows;namespace WpfApp1 {/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window,INotifyPropertyChanged{#region 数据绑定的固定写法private string _userName;private string _passWord;public string UserName {get { return _userName; }set { _userName value;RaisePropertyChanged(UserName);} }public string PassWord {get { return _passWord; } set {_passWord value;RaisePropertyChanged(PassWord);} }public event PropertyChangedEventHandler PropertyChanged;private void RaisePropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}#endregionpublic MainWindow(){InitializeComponent();this.DataContext this;}/// summary/// 登录按钮/// /summary/// param namesender/param/// param namee/paramprivate void Button_Click(object sender, RoutedEventArgs e){Console.WriteLine(${UserName}-{PassWord});UserName Admin;PassWord 123;}} } 8、MVVM(与 7 是同一个界面) MVVM是为里前后端的分离 MVVM与MVCVM 是对 C 的升级依靠的是 双向的数据属性 和 单向的命令属性 V 的修改 不会影响到 其他部分代码的编译 MVVM 和 MVC 的区别 MVVM M Model V View VM ViewModel MVC M Model V View C Control 8-1.1 带参的方法的写法 传入 Tag Button Grid.Row0 Command{Binding ClickBtn} Taga CommandParameter{Binding RelativeSource{RelativeSource Self}, PathTag}a/Buttonpublic ICommand ClickBtn {get{return new ExecuteCommond((param) {// param 是 CommandParameter 传递的值string tag param as string;Console.WriteLine($Tag: {tag});});} }传入控件自身 Button Grid.Row0 Command{Binding ClickBtn} Taga CommandParameter{Binding RelativeSource{RelativeSource Self}}a/Buttonpublic ICommand ClickBtn {get{return new ExecuteCommond((param) {if (param is Button button){var tag button.Tag; // 获取按钮的Tag属性Console.WriteLine($Tag: {tag});}});} }多种入参的 ICommand 的实现 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input;namespace QIPWaterDeal.ViewModel {public class ExecuteCommond : ICommand{/// summary/// 判断命令是否可以执行/// /summaryprivate readonly Funcbool _canExecute;/// summary/// 执行无参数的操作/// /summaryprivate readonly Action _execute;/// summary/// 执行带参数的操作/// /summaryprivate readonly Actionobject _executeWithParameter;/// summary/// 构造方法无参数版本/// /summarypublic ExecuteCommond(Action execute, Funcbool canExecute null){_execute execute;_canExecute canExecute;}/// summary/// 构造方法带参数版本/// /summarypublic ExecuteCommond(Actionobject executeWithParameter, Funcbool canExecute null){_executeWithParameter executeWithParameter;_canExecute canExecute;}public event EventHandler CanExecuteChanged;/// summary/// 是否可以执行命令/// /summarypublic bool CanExecute(object parameter){return _canExecute null || _canExecute();}/// summary/// 执行命令/// /summarypublic void Execute(object parameter){if (_execute ! null){_execute.Invoke();}else if (_executeWithParameter ! null){_executeWithParameter.Invoke(parameter);}}/// summary/// 通知CanExecute状态发生变化/// /summarypublic void RaiseCanExecuteChanged(){CanExecuteChanged?.Invoke(this, EventArgs.Empty);}} } 8-2 MVVM的另一种实践对 进行包装 一个实际的例子 MainWindow.xml Window x:ClassWpfApp1.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlTitle登录界面 Height270 Width500 ResizeModeNoResizeGridStackPanel HorizontalAlignmentCenter VerticalAlignmentCenterTextBox x:Nameinput1 Width100 Height24 Margin3 Text{Binding Input1}/TextBoxTextBox x:Nameinput2 Width100 Height24 Margin3 Text{Binding Input2}/TextBoxTextBox x:Nameinput3 Width100 Height24 Margin3 Text{Binding Input3}/TextBoxButton x:Namebtn1 Width100 Height24 Margin3 ContentAdd Command{Binding AddCommand}/Button/StackPanel/Grid /Window NotificationObject using System.ComponentModel;namespace WpfApp1 {/// summary/// VM 的基类/// /summarypublic class NotificationObject:INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;public void RaisePropertyChange(string propertyName){if(this.PropertyChanged ! null){this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs(propertyName));}}} } DelegateCommand using System; using System.Windows.Input;namespace WpfApp1 {public class DelegateCommand:ICommand{public bool CanExecute(object parameter){if(this.CanExecuteFunc null){return true;}return this.CanExecuteFunc(parameter);}public event EventHandler CanExecuteChanged;public void Execute(object parameter){if(this.ExecuteAction null){return;}this.ExecuteAction(parameter);}public Actionobject ExecuteAction { get; set; }public Funcobject,bool CanExecuteFunc { get; set; }} } MainWindowViewModel using System;namespace WpfApp1 {internal class MainWindowViewModel : NotificationObject{#region 数据属性private double input1;public double Input1 {get{ return input1;}set { input1 value;this.RaisePropertyChange(nameof(Input1));}}private double input2;public double Input2 {get{return input2;}set{input2 value;this.RaisePropertyChange(nameof(Input2));}}private double input3;public double Input3 {get {return input3;}set {input3 value;this.RaisePropertyChange(nameof(Input3));}}#endregion#region 命令属性public DelegateCommand AddCommand { get; set; }private void Add(object parameter){this.Input3 this.Input1 this.Input2;}public MainWindowViewModel(){this.AddCommand new DelegateCommand();this.AddCommand.ExecuteAction new Actionobject(this.Add);}#endregion} } 8-3、利用 特性反射优化数据变更通知接口的写法 9、写一个自定义控件添加 自定义 依赖属性 字典资源 加入字典资源 继承 Button 的自定义控件 使用 10、导入程序集和引用其中的名称空间 然后选 带 Framework 的 UserControl x:ClassWpfControlLibrary3.UserControl1xmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006 xmlns:dhttp://schemas.microsoft.com/expression/blend/2008 xmlns:localclr-namespace:WpfControlLibrary3mc:Ignorabled d:DesignHeight160 d:DesignWidth240GridCanvasLabel Canvas.Left12 Canvas.Top12 Content第一部分 Height28 Namelabel1/Label Canvas.Left12 Canvas.Top46 Content第二部分 Height28 Namelabel2/Label Canvas.Left12 Canvas.Top80 Content第三部分 Height28 Namelabel3/TextBox Canvas.Left88 Canvas.Top14 Height23 NametextBox1 Width140/TextBox Canvas.Left88 Canvas.Top48 Height23 NametextBox2 Width140/TextBox Canvas.Left88 Canvas.Top82 Height23 NametextBox3 Width140/Button Canvas.Left88 Canvas.Top125 Content计算 Height23 Namebutton1 Width140 Clickbutton_Click//Canvas/Grid /UserControl 添加引用 11、一些 x 命名空间的使用 x:Class x:ClassModifier x:Name x:FieldModifier 12、在WPF中加载 Winform 的 Form 1、在wpf 中添加引用 System.Windows.Forms.Integration 和 System.Windows.Forms.Integration 注System.Windows.Forms.Integration 在 Net Formwork 4.7.2 中叫 WindowsFormsIntegration 2、创建用户控件 在wpf 项目中创建 winform 控件 using System.Windows.Forms; using WindowsFormsControlLibrary1;namespace WpfApp1 {public partial class UserControl1 : UserControl{private Form1 _form1;public UserControl1(){InitializeComponent();_form1 new Form1();_form1.TopLevel false;_form1.Dock DockStyle.Fill;this.Controls.Add(_form1);_form1.Show();}} }在 主界面中 WindowsFormsHost 加入标签在代码中加载 Winform 的控件借助Winform控件 加载 winform 窗体 GridWindowsFormsHost NamewindowsFormsHost //Grid using System.Windows; namespace WpfApp1 {/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window{public MainWindow(){InitializeComponent();UserControl1 userControl1 new UserControl1();windowsFormsHost.Child userControl1;}} } 13、动画 动画有三种 线性动画DouleAnmim 关键帧动画DoubleAnimationUsingkeyFrams 路径动画DoubleAnimationUsingPath GridStackPanelButton x:Namebtn Width100 Height24 Content带动画的按钮 ClickButton_Click/Button x:Namebtn2 Width100 Height24 Content带动画的按钮 ClickButton_Click2/Button x:Namebtn3 Width100 Height24 Content带动画的按钮 ClickButton_Click3//StackPanel/Grid#define C using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; namespace WpfApp1 {/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private void Button_Click(object sender, RoutedEventArgs e){//创建一个双精度的动画DoubleAnimation animation new DoubleAnimation();animation.From btn.Width;//设置动画的初始值animation.To btn.Width - 30;//设置动画的结束值animation.Duration TimeSpan.FromSeconds(2);//设置动画的持续时间//在当前按钮上实行该动画btn.BeginAnimation(Button.WidthProperty,animation);}private void Button_Click2(object sender, RoutedEventArgs e){//创建一个双精度的动画DoubleAnimation animation new DoubleAnimation();animation.From btn2.Width;//设置动画的初始值animation.To btn2.Width - 30;//设置动画的结束值animation.Duration TimeSpan.FromSeconds(2);//设置动画的持续时间animation.AutoReverse true; //是否往返执行animation.RepeatBehavior RepeatBehavior.Forever; //执行周期//在当前按钮上实行该动画btn2.BeginAnimation(Button.WidthProperty,animation);}private void Button_Click3(object sender, RoutedEventArgs e){//创建一个双精度的动画DoubleAnimation animation new DoubleAnimation();animation.From btn3.Width;//设置动画的初始值animation.To btn3.Width - 30;//设置动画的结束值animation.Duration TimeSpan.FromSeconds(2);//设置动画的持续时间animation.AutoReverse true; //是否往返执行animation.RepeatBehavior new RepeatBehavior(5);//重复5次animation.Completed Animation_Completed;//动画结束的回调//在当前按钮上实行该动画btn3.BeginAnimation(Button.WidthProperty,animation);}private void Animation_Completed(object sender,EventArgs e){btn3.Content 动画已完成;}}} 14、WPF 和 Prism 其他 1、获取当前文件目录 string currentDirectory AppDomain.CurrentDomain.BaseDirectory;
http://www.dnsts.com.cn/news/271850.html

相关文章:

  • 网站建设意思vps wordpress cpu占用过高
  • 建立网站需要哪些手续中国菲律宾世预赛直播
  • 河南网站域名备案有意思网站推荐
  • 网站模板哪个网站好免费h5在线制作平台
  • 国外 网站有做验证码吗兰州装修公司报价明细表
  • 做公司永久免费网站什么好如何看自己网站流量
  • 帝国cms 网站搬家成都兼职建设网站
  • 汕头网站建设搭建商丘网站制作的流程
  • 中国空间站最新消息新闻室内装饰设计说明
  • 网站子页设计广东水利建设与管理信息网站
  • 鄂州第一官方网站八年级信息做网站所用软件
  • 凡科可以建设多个网站吗中国建设教育协会网站培训中心
  • 网站遮罩是什么游戏软件开发公司排名
  • 如何实现企业网站推广的系统性个人社保缴费基数是什么意思
  • 加强普法网站建设的通知物联网卡一年服务费多少钱啊
  • 短视频分享网站开发做电影网站用什么程序
  • 公众号版影视网站开发国外画册设计网站
  • 广州找人做网站whois域名查询官网
  • 做门户网站服务器选择石狮住房和城乡建设网站
  • 品牌网站的目的做电商网站的设计思路有什么意思
  • 山东省环保厅官方网站建设项目网站建设超速云免费
  • 湖南吉首建设官方网站公司网站开发的流程
  • 网站运营目标网站上的地图代码
  • 阳江市建设网站定制产品
  • 广州网站建设 骏域网站建设专家什么网站系统做的最好
  • 重庆网站推广系统如何给网站做排名
  • 微网站是什么网站建设中界面模板下载
  • 网站设计制作自己怎么做一个企业官网
  • 深圳专业做网站设计公司wordpress视频播放卡
  • 建设网站为什么要虚拟主机wordpress adsense integrator