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

WPF中如何简单的使用MvvmLight创建一个项目并进行 增删改查

第一步:创建项目后下载如下两个NuGet程序包,然后删除删掉using Microsoft.Practices.ServiceLocation; 并且引入using CommonServiceLocator;

 

 

 

 第二步:删除原来的XAML文件并创建如下的包结构然后创建一个在View文件夹中创建一个Main窗体   再将App.XAML中的StartupUri修改为View/Main.xaml

 

 

 

 第三步:创建Model层中的文件UserInfo和Todo

 UserInfo的类如下:

using GalaSoft.MvvmLight;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WPF练习12简单的项目.Model
{
    public class UserInfo : ObservableObject
    {
        [Key]
        public int UserId { get; set; }

        [Required(ErrorMessage = "账号必填")]
        [Column(TypeName = "varchar(50)")]
        public string Account { get; set; }

        [Required(ErrorMessage = "密码必填")]
        [Column(TypeName = "varchar(50)")]
        public string Pwd { get; set; }
    }
}

 Todo的类如下:

 

using GalaSoft.MvvmLight;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WPF练习12简单的项目.Model
{
    public class Todo:ObservableObject
    {
        [Key]
        public int TodoId { get; set; }

        [Required(ErrorMessage = "任务标题必填")]
        [Column(TypeName = "varchar(50)")]
        public string Title { get; set; }

        [Column(TypeName = "varchar(150)")]
        public string Detail { get; set; }

        [Required(ErrorMessage = "是否完成必填")]
        [Column(TypeName = "bit")]
        public bool IsCompleted { get; set; } = false;

        [Required(ErrorMessage = "创建人Id必填")]
        [Column(TypeName = "int")]
        public int CreateUserId { get; set; }

        [Required(ErrorMessage = "创建日期必填")]
        [Column(TypeName = "datetime")]
        public DateTime CreateTime { get; set; } = DateTime.Now;
    }
}

 第四步:创建Service层IUserInfoService接口和ITodoService接口

IUserInfoService接口如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习12简单的项目.Model;

namespace WPF练习12简单的项目.Service
{
    public interface IUserInfoService
    {
        bool Add(UserInfo model);
        bool Delete(int id);
        bool Update(UserInfo model);
        List<UserInfo> GetList(string strWhere);
        List<UserInfo> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex);
        UserInfo GetModel(int id);
    }
}

ITodoService接口如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习12简单的项目.Model;

namespace WPF练习12简单的项目.Service
{
    public interface ITodoService
    {
        bool Add(Todo model);
        bool Delete(int id);
        bool Update(Todo model);
        List<Todo> GetList(string strWhere);
        List<Todo> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex);
        int GetCount(string strWhere);
        Todo GetModel(int id);
    }
}

 第五步:配置连接字符串 并将连接的内容封装到Tool文件夹中的ConstHelper

 

 ConstHelper类如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPF练习12简单的项目.Tool
{
    public static class ConstHelper
    {
        public static string ConnectionString { get; } = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
    }
}

第六步:在ServiceImpl文件夹实现Service层中的接口

UserInfoService类如下:

using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习12简单的项目.Model;
using WPF练习12简单的项目.Service;
using WPF练习12简单的项目.Tool;

namespace WPF练习12简单的项目.ServiceImpl
{
    public class UserInfoService:IUserInfoService
    {
        public bool Add(UserInfo model)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "INSERT INTO UserInfo(Account, Pwd) VALUES (@Account, @Pwd)";
                return conn.Execute(sql, model) > 0;
            }
        }

        public bool Delete(int id)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "DELETE FROM UserInfo WHERE UserId=@UserId";
                var paramter = new { UserId = id };
                return conn.Execute(sql, paramter) > 0;
            }
        }

        public List<UserInfo> GetList(string strWhere)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "SELECT UserId, Account, Pwd FROM UserInfo WHERE 1=1 ";
                if (!string.IsNullOrEmpty(strWhere)) sql += $" AND {strWhere}";
                return conn.Query<UserInfo>(sql).ToList();
            }
        }

        public List<UserInfo> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                StringBuilder sql = new StringBuilder();
                sql.Append("SELECT * FROM ( ");
                sql.Append(" SELECT ROW_NUMBER() OVER (");

                if (!string.IsNullOrEmpty(orderBy.Trim()))
                    sql.Append("ORDER BY T." + orderBy);
                else
                    sql.Append("ORDER BY T.UserId DESC");

                sql.Append(")AS Row, T.*  FROM [User] T ");
                if (!string.IsNullOrEmpty(strWhere.Trim()))
                {
                    sql.Append(" WHERE " + strWhere);
                }
                sql.Append(" ) TT");
                sql.AppendFormat(" WHERE TT.Row BETWEEN {0} AND {1}", startIndex, endIndex);

                return conn.Query<UserInfo>(sql.ToString()).ToList();
            }
        }

        public UserInfo GetModel(int id)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "SELECT UserId, Account, Pwd FROM UserInfo WHERE UserId=@UserId";
                var parameter = new { UserId = id };
                return conn.QueryFirstOrDefault<UserInfo>(sql, parameter);
            }
        }

        public bool Update(UserInfo model)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "UPDATE UserInfo SET Account=@Account, Pwd=@Pwd WHERE UserId=@UserId";
                return conn.Execute(sql, model) > 0;
            }
        }
    }
}

TodoService类如下:

using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习12简单的项目.Model;
using WPF练习12简单的项目.Service;
using WPF练习12简单的项目.Tool;

namespace WPF练习12简单的项目.ServiceImpl
{
    public class TodoService : ITodoService
    {
        public bool Add(Todo model)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "INSERT INTO [Todo](Title, Detail, IsCompleted, CreateUserId, CreateTime) VALUES (@Title, @Detail, @IsCompleted, @CreateUserId, @CreateTime)";
                return conn.Execute(sql, model) > 0;
            }
        }

        public bool Delete(int id)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "DELETE FROM [Todo] WHERE TodoId=@TodoId";
                var paramter = new { TodoId = id };
                return conn.Execute(sql, paramter) > 0;
            }
        }

        public List<Todo> GetList(string strWhere)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "SELECT TodoId, Title, Detail, IsCompleted, CreateUserId, CreateUserName, CreateTime FROM [TodoView] WHERE 1=1 ";
                if (!string.IsNullOrEmpty(strWhere)) sql += $" AND {strWhere}";
                return conn.Query<Todo>(sql).ToList();
            }
        }

        public List<Todo> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                StringBuilder sql = new StringBuilder();
                sql.Append("SELECT * FROM ( ");
                sql.Append(" SELECT ROW_NUMBER() OVER (");

                if (!string.IsNullOrEmpty(orderBy.Trim()))
                    sql.Append("ORDER BY T." + orderBy);
                else
                    sql.Append("ORDER BY T.TodoId DESC");

                sql.Append(")AS Row, T.*  FROM [TodoView] T ");
                if (!string.IsNullOrEmpty(strWhere.Trim()))
                {
                    sql.Append(" WHERE " + strWhere);
                }
                sql.Append(" ) TT");
                sql.AppendFormat(" WHERE TT.Row BETWEEN {0} AND {1}", startIndex, endIndex);

                return conn.Query<Todo>(sql.ToString()).ToList();
            }
        }

        public int GetCount(string strWhere)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "SELECT COUNT(TodoId) FROM [Todo] WHERE 1=1 ";
                if (!string.IsNullOrEmpty(strWhere)) sql += $" AND {strWhere}";
                return conn.ExecuteScalar<int>(sql);
            }
        }

        public Model.Todo GetModel(int id)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "SELECT TodoId, Title, Detail, IsCompleted, CreateUserId, CreateTime FROM [Todo] WHERE TodoId=@TodoId";
                var parameter = new { TodoId = id };
                return conn.QueryFirstOrDefault<Model.Todo>(sql, parameter);
            }
        }

        public bool Update(Model.Todo model)
        {
            using (var conn = new SqlConnection(ConstHelper.ConnectionString))
            {
                conn.Open();
                var sql = "UPDATE [Todo] SET Title=@Title, Detail=@Detail, IsCompleted=@IsCompleted, CreateUserId=@CreateUserId, CreateTime=@CreateTime WHERE TodoId=@TodoId";
                return conn.Execute(sql, model) > 0;
            }
        }
    }
}

第七步:在View文件夹中创建Login.XAML文件 并将App.XAML文件进行修改

1.将StartupUri删除

2.添加 ShutdownMode="OnExplicitShutdown"和Startup="Application_Startup"


http://www.kler.cn/a/379317.html

相关文章:

  • 【力扣 + 牛客 | SQL题 | 每日5题】牛客SQL热题216,217,223
  • 气象大模型学习笔记
  • HTML 框架
  • jmeter脚本-请求体设置变量and请求体太长的处理
  • GitHub上传自己的项目
  • VisionPro —— CogPatInspectTool对比工具
  • 【屏幕驱动移植记录】
  • C#如何封装将函数封装为接口dll?
  • 集成学习(2)
  • 前端学习-盒子模型(十八)
  • TensorRT-LLM笔记
  • 数据结构:总览
  • 九,数据类型存储
  • Kubernetes——part9-2 kubernetes集群java项目上云部署
  • 大模型微调
  • ubuntu离线部署ollama
  • Java毕业设计-基于微信小程序的校园二手物品交易系统的实现(V2.0)
  • docker build cache 占用磁盘空间很高
  • SQL,力扣题目1747,应该被禁止的 Leetflex 账户
  • 近期学习前端的心得
  • (三千字心得笔记)零基础C语言入门第七课——二维数组
  • 【面试经典150】day 11
  • 双分解+一区极光优化+Transformer!CEEMDAN-Kmeans-VMD-PLO-Transformer多元时序预测
  • Python 作用域浅析
  • 【LeetCode】每日一题 2024_11_1 超级饮料的最大强化能量(DP)
  • 【实战篇】requests库 - 有道云翻译爬虫 【附:代理IP的使用】