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

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

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

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

UserInfo的类如下:

cs 复制代码
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的类如下:

cs 复制代码
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接口如下:

cs 复制代码
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接口如下:

cs 复制代码
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类如下:

cs 复制代码
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类如下:

cs 复制代码
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类如下:

cs 复制代码
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"

相关推荐
九鼎科技-Leo12 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
麻花20131 天前
C#之WPF的C1FlexGrid空间的行加载事件和列事件变更处理动态加载的枚举值
开发语言·c#·wpf
lcintj1 天前
【WPF】Prism学习(九)
学习·wpf·prism
界面开发小八哥1 天前
界面控件DevExpress WPF中文教程:网格视图数据布局的列和卡片字段
wpf·界面控件·devexpress·ui开发·用户界面
△曉風殘月〆1 天前
如何在WPF中嵌入其它程序
wpf
Crazy Struggle1 天前
功能齐全的 WPF 自定义控件资源库(收藏版)
.net·wpf·ui控件库
shepherd枸杞泡茶1 天前
WPF动画
c#·.net·wpf
lcintj1 天前
【WPF】Prism学习(十)
学习·wpf·prism
wyh要好好学习1 天前
WPF数据加载时添加进度条
ui·wpf
code_shenbing1 天前
跨平台WPF框架Avalonia教程 三
前端·microsoft·ui·c#·wpf·跨平台·界面设计