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"

相关推荐
晚安苏州10 小时前
WPF DataTemplate 数据模板
wpf
甜甜不吃芥末1 天前
WPF依赖属性详解
wpf
Hat_man_1 天前
WPF制作图片闪烁的自定义控件
wpf
晚安苏州3 天前
WPF Binding 绑定
wpf·wpf binding·wpf 绑定
wangnaisheng3 天前
【WPF】RenderTargetBitmap的使用
wpf
dotent·3 天前
WPF 完美解决改变指示灯的颜色
wpf
orangapple5 天前
WPF 用Vlc.DotNet.Wpf实现视频播放、停止、暂停功能
wpf·音视频
ysdysyn5 天前
wpf mvvm 数据绑定数据(按钮文字表头都可以),根据长度进行换行,并把换行的文字居中
c#·wpf·mvvm
orangapple5 天前
WPF 使用LibVLCSharp.WPF实现视频播放、停止、暂停功能
wpf
晚安苏州5 天前
WPF ControlTemplate 控件模板
wpf