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

目录

开始前准备的数据库dbblog如下:

第一步:创建项目后下载四个NuGet程序包

第二步:删除原本的MainWindow.XAML文件 并创建如下的目录结构 然后在View文件夹下面创建Login.XAML和Main.XAML          并且在App.XAML中将启动项改为Login.XAML

1.View文件夹下面创建Login.XAML和Main.XAML 

2.在App.XAML中将启动项改为Login.XAML

第三步:在Model文件夹中创建BlogTypeInfo类,CommentInfo类,PostInfo类,UserInfo类 并在Model文件夹下的View文件夹中创建BlogTypeInfoView类,CommentInfoView类,PostInfoView类,UserInfoView类

BlogTypeInfo类如下:

CommentInfo类如下:

PostInfo类如下:

UserInfo类如下:

BlogTypeInfoView类如下:

CommentInfoView类如下:

PostInfoView类如下:

UserInfoView类如下:

第四步:在View文件夹中的UserControls文件夹中创建BlogType.XAML、Comment.XAML、Post.XAML、User.XAML

User.XAML如下:

Post.XAML如下:

Comment.XAML如下:

BlogType.XAML如下:

第五步:在Service文件夹下创建IBase 、IBlogTypeInfo、ICommentInfo、IPostInfo、IUserInfo

IBase如下:

IBlogTypeInfo如下:

ICommentInfo如下:

IPostInfo如下:

IUserInfo如下:

第六步:先配置好在APP.config中的connectionStrings并在Help文件夹中创建ConstHelper类中把connectionStrings放在里面 然后实现Service中的所有接口BlogTypeInfoService、CommentInfoService、PostInfoService、UserInfoService 

配置connectionStrings

ConstHelper如下:

BlogTypeInfoService如下:

CommentInfoService如下:

PostInfoService如下:

UserInfoService如下:

第七步:在App.cs文件中放入想要放入Ioc容器的对象

第八步:在Helper文件夹中创建LoginInfoHelper类存放登录的用户 并在ViewModel创建LoginViewModel类和MainViewModel类

LoginViewModel如下:

MainViewModel如下:

第九步:在Login.XAML和Main.XAML中写对应的前端代码

1.在Dict文件夹中创建LoginDictionary.xaml存放登录窗口的样式

 LoginDictionary.xaml如下:

2.App.XAML文件中存在共同的样式以及存放LoginDictionary.xaml的引用

3.在Login.XAML文件中创建上下文并创建基本样式 

4.在Main.XAML文件中创建上下文并创建基本样式 

效果如下:


开始前准备的数据库dbblog如下:

USE [dbblog]
GO
/****** Object:  Table [dbo].[UserInfo]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserInfo]([UserId] [int] IDENTITY(1,1) NOT NULL,[UserName] [varchar](20) NOT NULL,[UserPwd] [varchar](50) NOT NULL,[Phone] [varchar](20) NOT NULL,[NickName] [varchar](20) NOT NULL,[Logo] [image] NULL,[RealName] [varchar](20) NULL,[Sex] [bit] NULL,[Birthday] [datetime] NULL,[DataStatus] [int] NOT NULL,[CreateUserId] [int] NOT NULL,[CreateTime] [datetime] NOT NULL,[LastUpdateUserId] [int] NULL,[LastUpdateTime] [datetime] NULL,CONSTRAINT [PK_UserInfo] PRIMARY KEY CLUSTERED 
([UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[UserInfoView]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[UserInfoView]
as
select ui1.[UserId],ui1.[UserName],ui1.[UserPwd],ui1.[Phone],ui1.[NickName],ui1.[Logo],ui1.[RealName],ui1.[Sex],ui1.[Birthday],ui1.[DataStatus],case ui1.[DataStatus] when 0 then '正常' when 1 then '禁用' else '未知' end as DataStatusText,ui1.[CreateUserId],ui2.[UserName] as CreateUserName,ui1.[CreateTime],ui1.[LastUpdateUserId],ui3.[UserName] as LastUpdateUserName,ui1.[LastUpdateTime] from UserInfo as ui1
left join UserInfo as ui2 on ui1.CreateUserId = ui2.UserId
left join UserInfo as ui3 on ui1.LastUpdateUserId = ui2.UserId
GO
/****** Object:  Table [dbo].[BlogTypeInfo]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BlogTypeInfo]([BlogTypeId] [int] IDENTITY(1,1) NOT NULL,[TypeName] [varchar](50) NOT NULL,[ParentBlogTypeId] [int] NOT NULL,[DataStatus] [int] NOT NULL,[CreateUserId] [int] NOT NULL,[CreateTime] [datetime] NOT NULL,[LastUpdateUserId] [int] NULL,[LastUpdateTime] [datetime] NULL,CONSTRAINT [PK_BlogTypeInfo] PRIMARY KEY CLUSTERED 
([BlogTypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[BlogTypeInfoView]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[BlogTypeInfoView]
as
select bti.[BlogTypeId],bti.[TypeName],bti.[ParentBlogTypeId],bti2.[TypeName] as ParentBlogTypeName,bti.[DataStatus],case bti.[DataStatus] when 0 then '正常' when 1 then '禁用' else '未知' end as DataStatusText,bti.[CreateUserId],ui1.[UserName] as CreateUserName,bti.[CreateTime],bti.[LastUpdateUserId],ui2.[UserName] as LastUpdateUserName,bti.[LastUpdateTime] from blogtypeinfo as bti
left join blogtypeinfo as bti2 on bti.parentblogtypeid=bti2.blogtypeid
left join userinfo as ui1 on bti.createuserid=ui1.userid
left join userinfo as ui2 on bti.lastupdateuserid=ui2.userid
GO
/****** Object:  Table [dbo].[CommentInfo]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CommentInfo]([CommentId] [int] IDENTITY(1,1) NOT NULL,[CommentContent] [varchar](250) NOT NULL,[DataStatus] [int] NOT NULL,[CreateUserId] [int] NOT NULL,[CreateTime] [datetime] NOT NULL,[LastUpdateUserId] [int] NULL,[LastUpdateTime] [datetime] NULL,CONSTRAINT [PK_CommentInfo] PRIMARY KEY CLUSTERED 
([CommentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[CommentInfoView]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[CommentInfoView]
as
SELECT ci.[CommentId],ci.[CommentContent],ci.[DataStatus],case ci.[DataStatus] when 0 then '正常' when 1 then '禁用' else '未知' end as DataStatusText,ci.[CreateUserId],ui1.[UserName] as CreateUserName,ci.[CreateTime],ci.[LastUpdateUserId],ui2.[UserName] as LastUpdateUserName,ci.[LastUpdateTime]FROM [dbo].[CommentInfo] as cileft join userinfo as ui1 on ci.createuserid=ui1.userid
left join userinfo as ui2 on ci.lastupdateuserid=ui2.useridGO
/****** Object:  Table [dbo].[PostInfo]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PostInfo]([PostId] [int] IDENTITY(1,1) NOT NULL,[Title] [varchar](50) NOT NULL,[PostContent] [text] NOT NULL,[BlogTypeId] [int] NOT NULL,[LikeCount] [int] NOT NULL,[HateCount] [int] NOT NULL,[ReadCount] [int] NOT NULL,[CommentCount] [int] NOT NULL,[DataStatus] [int] NOT NULL,[CreateUserId] [int] NOT NULL,[CreateTime] [datetime] NOT NULL,[LastUpdateUserId] [int] NULL,[LastUpdateTime] [datetime] NULL,CONSTRAINT [PK_PostInfo] PRIMARY KEY CLUSTERED 
([PostId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[PostInfoView]    Script Date: 2024/11/5 17:42:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GOcreate view [dbo].[PostInfoView]
as
SELECT poi.[PostId],poi.[Title],poi.[PostContent],poi.[BlogTypeId],bti.[TypeName] as BlogTypeName,poi.[LikeCount],poi.[HateCount],poi.[ReadCount],poi.[CommentCount],poi.[DataStatus],case poi.[DataStatus] when 0 then '正常' when 1 then '禁用' else '未知' end as DataStatusText,poi.[CreateUserId],ui1.[UserName] as CreateUserName,poi.[CreateTime],poi.[LastUpdateUserId],ui2.[UserName] as LastUpdateUserName,poi.[LastUpdateTime]FROM [dbo].[PostInfo] as poileft join blogtypeinfo as bti on poi.blogtypeid=bti.blogtypeIdleft join userinfo as ui1 on poi.createuserid=ui1.userid
left join userinfo as ui2 on poi.lastupdateuserid=ui2.useridGO
ALTER TABLE [dbo].[BlogTypeInfo] ADD  CONSTRAINT [DF_BlogTypeInfo_DataStatus]  DEFAULT ((0)) FOR [DataStatus]
GO
ALTER TABLE [dbo].[BlogTypeInfo] ADD  CONSTRAINT [DF_BlogTypeInfo_CreateTime]  DEFAULT (getdate()) FOR [CreateTime]
GO
ALTER TABLE [dbo].[CommentInfo] ADD  CONSTRAINT [DF_CommentInfo_DataStatus]  DEFAULT ((0)) FOR [DataStatus]
GO
ALTER TABLE [dbo].[CommentInfo] ADD  CONSTRAINT [DF_CommentInfo_CreateTime]  DEFAULT (getdate()) FOR [CreateTime]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_LikeCount]  DEFAULT ((0)) FOR [LikeCount]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_HateCount]  DEFAULT ((0)) FOR [HateCount]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_ReadCount]  DEFAULT ((0)) FOR [ReadCount]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_CommentCount]  DEFAULT ((0)) FOR [CommentCount]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_DataStatus]  DEFAULT ((0)) FOR [DataStatus]
GO
ALTER TABLE [dbo].[PostInfo] ADD  CONSTRAINT [DF_PostInfo_CreateTime]  DEFAULT (getdate()) FOR [CreateTime]
GO
ALTER TABLE [dbo].[UserInfo] ADD  CONSTRAINT [DF_UserInfo_DataStatus]  DEFAULT ((0)) FOR [DataStatus]
GO
ALTER TABLE [dbo].[UserInfo] ADD  CONSTRAINT [DF_UserInfo_CreateTime]  DEFAULT (getdate()) FOR [CreateTime]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主键' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'BlogTypeId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'博客类型名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'TypeName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'父级类型名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'ParentBlogTypeId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据状态(0正常,1禁用)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'DataStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'CreateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'BlogTypeInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主键' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'CommentId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评论内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'CommentContent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据状态(0正常,1禁用)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'DataStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'CreateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CommentInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主键' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'PostId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'标题' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'Title'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'PostContent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'BlogTypeId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'点赞数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'LikeCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'踩数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'HateCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'阅读数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'ReadCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'评论数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'CommentCount'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据状态(0正常,1禁用)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'DataStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'CreateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'PostInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主键' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'UserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'密码' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'UserPwd'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'手机号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'Phone'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'昵称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'NickName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'RealName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'Sex'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'生日' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'Birthday'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'数据状态(0正常,1禁用)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'DataStatus'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'CreateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改人(外键)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateUserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'最后一次修改日期' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'UserInfo', @level2type=N'COLUMN',@level2name=N'LastUpdateTime'
GO

第一步:创建项目后下载四个NuGet程序包

第二步:删除原本的MainWindow.XAML文件 并创建如下的目录结构 然后在View文件夹下面创建Login.XAML和Main.XAML          并且在App.XAML中将启动项改为Login.XAML

1.View文件夹下面创建Login.XAML和Main.XAML 

2.在App.XAML中将启动项改为Login.XAML

第三步:在Model文件夹中创建BlogTypeInfo类,CommentInfo类,PostInfo类,UserInfo类 并在Model文件夹下的View文件夹中创建BlogTypeInfoView类,CommentInfoView类,PostInfoView类,UserInfoView类

BlogTypeInfo类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model
{public class BlogTypeInfo{public int BlogTypeId { get; set; }public string TypeName { get; set; }public int ParentBlogTypeId { get; set; }public int DataStatus { get; set; } = 0;public int CreateUserId { get; set; }public DateTime CreateTime { get; set; } = DateTime.Now;public int LastUpdateUserId { get; set; }public DateTime LastUpdateTime { get; set; }}
}

CommentInfo类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model
{public class CommentInfo{public int CommentId { get; set; }public string CommentContent { get; set; }public int DataStatus { get; set; } = 0;public int CreateUserId { get; set; }public DateTime CreateTime { get; set; } = DateTime.Now;public int LastUpdateUserId { get; set; }public DateTime LastUpdateTime { get; set; }}
}

PostInfo类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model
{public class PostInfo{public int PostId { get; set; }public string Title { get; set; }public string PostContent { get; set; }public int BlogTypeId { get; set; }public int LikeCount { get; set; } = 0;public int HateCount { get; set; } = 0;public int ReadCount { get; set; } = 0;public int CommentCount { get; set; } = 0;public int DataStatus { get; set; } = 0;public int CreateUserId { get; set; }public DateTime CreateTime { get; set; } = DateTime.Now;public int LastUpdateUserId { get; set; }public DateTime LastUpdateTime { get; set; }}
}

UserInfo类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model
{public class UserInfo{public int UserId { get; set; }public string UserName { get; set; }public string UserPwd { get; set; }public string Phone { get; set; }public string NickName { get; set; }public byte[] Logo { get; set; }public string RealName { get; set; }public bool Sex { get; set; }public DateTime Birthday { get; set; }public int DataStatus { get; set; } = 0;public int CreateUserId { get; set; }public DateTime CreateTime { get; set; } = DateTime.Now;public int LastUpdateUserId { get; set; }public DateTime LastUpdateTime { get; set; }}
}

BlogTypeInfoView类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model.View
{public class BlogTypeInfoView : BlogTypeInfo{public string ParentBlogTypeName { get; set; }public string DataStatusText { get; set; }public string CreateUserName { get; set; }public int LastUpdateUserName { get; set; }}
}

CommentInfoView类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model.View
{public class CommentInfoView : CommentInfo{public string DataStatusText { get; set; }public string CreateUserName { get; set; }public int LastUpdateUserName { get; set; }}
}

PostInfoView类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model.View
{public class PostInfoView : PostInfo{public string BlogTypeName { get; set; }public string DataStatusText { get; set; }public string CreateUserName { get; set; }public int LastUpdateUserName { get; set; }}
}

UserInfoView类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Model.View
{public class UserInfoView : UserInfo{public string DataStatusText { get; set; }public string CreateUserName { get; set; }public int LastUpdateUserName { get; set; }}
}

第四步:在View文件夹中的UserControls文件夹中创建BlogType.XAML、Comment.XAML、Post.XAML、User.XAML

User.XAML如下:

<UserControl x:Class="WPF练习13简单的项目.View.UserControls.User"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WPF练习13简单的项目.View.UserControls"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"><Grid><TextBlock Text="1" /></Grid>
</UserControl>

Post.XAML如下:

<UserControl x:Class="WPF练习13简单的项目.View.UserControls.Post"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WPF练习13简单的项目.View.UserControls"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"><Grid><TextBlock Text="2" /></Grid>
</UserControl>

Comment.XAML如下:

<UserControl x:Class="WPF练习13简单的项目.View.UserControls.Comment"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WPF练习13简单的项目.View.UserControls"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"><Grid><TextBlock Text="3" /></Grid>
</UserControl>

BlogType.XAML如下:

<UserControl x:Class="WPF练习13简单的项目.View.UserControls.BlogType"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WPF练习13简单的项目.View.UserControls"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"><Grid><TextBlock Text="4" /></Grid>
</UserControl>

第五步:在Service文件夹下创建IBase 、IBlogTypeInfo、ICommentInfo、IPostInfo、IUserInfo

IBase如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Service
{public interface IBase<T,K>{/// <summary>/// 添加数据/// </summary>/// <param name="model">模型</param>/// <returns>布尔</returns>bool Add(T model);/// <summary>/// 删除/// </summary>/// <param name="id">主键</param>/// <returns>布尔</returns>bool Delete(int id);/// <summary>/// 分页获取数据/// </summary>/// <param name="strWhere">查询条件</param>/// <param name="orderBy">排序字段</param>/// <param name="startIndex">起始索引</param>/// <param name="endIndex">结束索引</param>/// <returns>列表,关联视图模型K</returns>List<K> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex);/// <summary>/// 获取单个模型/// </summary>/// <param name="id">主键</param>/// <returns>泛型T</returns>T GetModel(int id);/// <summary>/// 修改/// </summary>/// <param name="model">模型</param>/// <returns>布尔</returns>bool Update(T model);}
}

IBlogTypeInfo如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Model;namespace WPF练习13简单的项目.Service
{public interface IBlogTypeInfo : IBase<BlogTypeInfo, BlogTypeInfoView>{}
}

ICommentInfo如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Model;namespace WPF练习13简单的项目.Service
{public interface ICommentInfo : IBase<CommentInfo, CommentInfoView>{}
}

IPostInfo如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Model;namespace WPF练习13简单的项目.Service
{public interface IPostInfo : IBase<PostInfo, PostInfoView>{}
}

IUserInfo如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Model.View;namespace WPF练习13简单的项目.Service
{public interface IUserInfo : IBase<UserInfo, UserInfoView>{UserInfo Login(string userName, string userPwd);}
}

第六步:先配置好在APP.config中的connectionStrings并在Help文件夹中创建ConstHelper类中把connectionStrings放在里面 然后实现Service中的所有接口BlogTypeInfoService、CommentInfoService、PostInfoService、UserInfoService 

配置connectionStrings

ConstHelper如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace WPF练习13简单的项目.Helper
{public static class ConstHelper{public static string ConnString { get; } = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;}
}

BlogTypeInfoService如下:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Service;
using Dapper;
using WPF练习13简单的项目.Helper;namespace WPF练习13简单的项目.ServiceImpl
{public class BlogTypeInfoService : IBlogTypeInfo{public bool Add(BlogTypeInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "INSERT INTO BlogTypeInfo(TypeName,ParentBlogTypeId,DataStatus,CreateUserId,CreateTime,LastUpdateUserId,LastUpdateTime) VALUES (@TypeName,@ParentBlogTypeId,@DataStatus,@CreateUserId,@CreateTime,@LastUpdateUserId,@LastUpdateTime)";return conn.Execute(sql, model) > 0;}}public bool Delete(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE BlogTypeInfo Set DataStatus=1 WHERE BlogTypeId=@BlogTypeId";var param = new { BlogTypeId = id };return conn.Execute(sql, param) > 0;}}public List<BlogTypeInfoView> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex){using (var conn = new SqlConnection(ConstHelper.ConnString)){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);elsesql.Append("ORDER BY T.UserId DESC");sql.Append(")AS Row, T.*  FROM BlogTypeInfoView 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<BlogTypeInfoView>(sql.ToString()).ToList();}}public BlogTypeInfo GetModel(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "SELECT * FROM BlogTypeInfo WHERE BlogTypeId=@BlogTypeId";var param = new { BlogTypeId = id };return conn.QueryFirstOrDefault<BlogTypeInfo>(sql, param);}}public bool Update(BlogTypeInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE BlogTypeInfo SET TypeName=@TypeName,ParentBlogTypeId=@ParentBlogTypeId,DataStatus=@DataStatus,CreateUserId=@CreateUserId,CreateTime=@CreateTime,LastUpdateUserId=@LastUpdateUserId,LastUpdateTime=@LastUpdateTime WHERE BlogTypeId=@BlogTypeId";return conn.Execute(sql, model) > 0;}}}
}

CommentInfoService如下:

using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Helper;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Service;namespace WPF练习13简单的项目.ServiceImpl
{public class CommentInfoService : ICommentInfo{public bool Add(CommentInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "INSERT INTO CommentInfo(CommentContent,DataStatus,CreateUserId,CreateTime,LastUpdateUserId,LastUpdateTime) VALUES (@CommentContent,@DataStatus,@CreateUserId,@CreateTime,@LastUpdateUserId,@LastUpdateTime)";return conn.Execute(sql, model) > 0;}}public bool Delete(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE CommentInfo Set DataStatus=1 WHERE CommentId=@CommentId";var param = new { CommentId = id };return conn.Execute(sql, param) > 0;}}public List<CommentInfoView> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex){using (var conn = new SqlConnection(ConstHelper.ConnString)){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);elsesql.Append("ORDER BY T.UserId DESC");sql.Append(")AS Row, T.*  FROM CommentInfoView 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<CommentInfoView>(sql.ToString()).ToList();}}public CommentInfo GetModel(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "SELECT * FROM CommentInfo WHERE CommentId=@CommentId";var param = new { CommentId = id };return conn.QueryFirstOrDefault<CommentInfo>(sql, param);}}public bool Update(CommentInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE CommentInfo SET CommentContent=@CommentContent,DataStatus=@DataStatus,CreateUserId=@CreateUserId,CreateTime=@CreateTime,LastUpdateUserId=@LastUpdateUserId,LastUpdateTime=@LastUpdateTime WHERE CommentId=@CommentId";return conn.Execute(sql, model) > 0;}}}
}

PostInfoService如下:

using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF练习13简单的项目.Helper;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Service;namespace WPF练习13简单的项目.ServiceImpl
{public class PostInfoService: IPostInfo{public bool Add(PostInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "INSERT INTO PostInfo(Title,PostContent,BlogTypeId,LikeCount,HateCount,ReadCount,CommentCount,DataStatus,CreateUserId,CreateTime,LastUpdateUserId,LastUpdateTime) VALUES (@Title,@PostContent,@BlogTypeId,@LikeCount,@HateCount,@ReadCount,@CommentCount,@DataStatus,@CreateUserId,@CreateTime,@LastUpdateUserId,@LastUpdateTime)";return conn.Execute(sql, model) > 0;}}public bool Delete(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE PostInfo Set DataStatus=1 WHERE PostId=@PostId";var param = new { PostId = id };return conn.Execute(sql, param) > 0;}}public List<PostInfoView> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex){using (var conn = new SqlConnection(ConstHelper.ConnString)){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);elsesql.Append("ORDER BY T.UserId DESC");sql.Append(")AS Row, T.*  FROM PostInfoView 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<PostInfoView>(sql.ToString()).ToList();}}public PostInfo GetModel(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "SELECT * FROM PostInfo WHERE PostId=@PostId";var param = new { PostId = id };return conn.QueryFirstOrDefault<PostInfo>(sql, param);}}public bool Update(PostInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE PostInfo SET Title=@Title,PostContent=@PostContent,BlogTypeId=@BlogTypeId,LikeCount=@LikeCount,HateCount=@HateCount,ReadCount=@ReadCount,CommentCount=@CommentCount,DataStatus=@DataStatus,CreateUserId=@CreateUserId,CreateTime=@CreateTime,LastUpdateUserId=@LastUpdateUserId,LastUpdateTime=@LastUpdateTime WHERE PostId=@PostId";return conn.Execute(sql, model) > 0;}}}
}

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练习13简单的项目.Helper;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Model.View;
using WPF练习13简单的项目.Service;namespace WPF练习13简单的项目.ServiceImpl
{public class UserInfoService: IUserInfo{public bool Add(UserInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "INSERT INTO UserInfo(UserName,UserPwd,Phone,NickName,Logo,RealName,Sex,Birthday,DataStatus,CreateUserId,CreateTime,LastUpdateUserId,LastUpdateTime) VALUES (@UserName,@UserPwd,@Phone,@NickName,@Logo,@RealName,@Sex,@Birthday,@DataStatus,@CreateUserId,@CreateTime,@LastUpdateUserId,@LastUpdateTime)";return conn.Execute(sql, model) > 0;}}public bool Delete(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE UserInfo Set DataStatus=1 WHERE UserId=@UserId";var param = new { UserId = id };return conn.Execute(sql, param) > 0;}}public List<UserInfoView> GetListByPage(string strWhere, string orderBy, int startIndex, int endIndex){using (var conn = new SqlConnection(ConstHelper.ConnString)){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);elsesql.Append("ORDER BY T.UserId DESC");sql.Append(")AS Row, T.*  FROM UserInfoView 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<UserInfoView>(sql.ToString()).ToList();}}public UserInfo GetModel(int id){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "SELECT * FROM UserInfo WHERE UserId=@UserId";var param = new { UserId = id };return conn.QueryFirstOrDefault<UserInfo>(sql, param);}}public UserInfo Login(string userName, string userPwd){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "SELECT * FROM UserInfo WHERE UserName=@UserName AND UserPwd=@UserPwd";var param = new { UserName = userName, UserPwd = userPwd };return conn.QueryFirstOrDefault<UserInfo>(sql, param);}}public bool Update(UserInfo model){using (var conn = new SqlConnection(ConstHelper.ConnString)){conn.Open();var sql = "UPDATE UserInfo SET UserName=@UserName,UserPwd=@UserPwd,Phone=@Phone,NickName=@NickName,Logo=@Logo,RealName=@RealName,Sex=@Sex,Birthday=@Birthday,DataStatus=@DataStatus,CreateUserId=@CreateUserId,CreateTime=@CreateTime,LastUpdateUserId=@LastUpdateUserId,LastUpdateTime=@LastUpdateTime WHERE UserId=@UserId";return conn.Execute(sql, model) > 0;}}}
}

第七步:在App.cs文件中放入想要放入Ioc容器的对象

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using WPF练习13简单的项目.Service;
using WPF练习13简单的项目.ServiceImpl;
using WPF练习13简单的项目.View;
using WPF练习13简单的项目.View.UserControls;namespace WPF练习13简单的项目
{/// <summary>/// App.xaml 的交互逻辑/// </summary>public partial class App : Application{public IServiceProvider Services { get; }public App(){Services = ConfigurationServices();}public static new App Current { get { return (App)Application.Current; } }private IServiceProvider ConfigurationServices(){ServiceCollection services = new ServiceCollection();// 放窗体services.AddSingleton<Main>();// 放用户控件services.AddSingleton<BlogType>();services.AddSingleton<Comment>();services.AddSingleton<Post>();services.AddSingleton<User>();// 放服务services.AddSingleton<IBlogTypeInfo, BlogTypeInfoService>();services.AddSingleton<ICommentInfo, CommentInfoService>();services.AddSingleton<IPostInfo, PostInfoService>();services.AddSingleton<IUserInfo, UserInfoService>();return services.BuildServiceProvider();}}
}

第八步:在Helper文件夹中创建LoginInfoHelper类存放登录的用户 并在ViewModel创建LoginViewModel类和MainViewModel类

 

using CTMVVMDemo.Model;namespace CTMVVMDemo.Helper
{public static class LoginInfoHelper{public static UserInfo CurrentUser { get; set; }}
}

LoginViewModel如下:

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using WPF练习13简单的项目.Helper;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Service;
using WPF练习13简单的项目.View;namespace WPF练习13简单的项目.ViewModel
{public class LoginViewModel : ObservableObject{private readonly IUserInfo userService;public LoginViewModel(){userService = App.Current.Services.GetService<IUserInfo>();}private string userName;public string UserName{get => userName;set => SetProperty(ref userName, value);}private SecureString password;public SecureString Password{get => password;set => SetProperty(ref password, value);}public RelayCommand<Login> LoginCommand{get{return new RelayCommand<Login>((loginWin) =>{Button btnLogin = loginWin.FindName("btnLogin") as Button;if (btnLogin != null) btnLogin.Focus();UserInfo userInfo = userService.Login(UserName, SecureStringToString(Password));if (userInfo == null){MessageBox.Show("登录失败,请检查账号或密码是否正确!", "错误", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);return;}LoginInfoHelper.CurrentUser = userInfo;loginWin.Hide();var mainWin = App.Current.Services.GetService<Main>();mainWin.Show();});}}public RelayCommand<object> PasswordChangedCommand{get{return new RelayCommand<object>((obj) =>{var passwordBox = obj as PasswordBox;if (passwordBox != null) Password = passwordBox.SecurePassword;});}}/// <summary>/// 将 SecureString 类型的数据转换为普通的字符串类型。 https://www.cnblogs.com/CDRPS/p/18156533/// </summary>/// <param name="secureString">要转换的 SecureString 对象。</param>/// <returns>转换后的字符串,如果转换失败则返回空字符串。</returns>private string SecureStringToString(SecureString secureString){// 初始化指针IntPtr ptr = IntPtr.Zero;try{// 将 SecureString 转换为指针ptr = Marshal.SecureStringToGlobalAllocUnicode(secureString);if (ptr != IntPtr.Zero){// 将指针中的数据复制到一个普通的字符串return Marshal.PtrToStringUni(ptr);}else{return string.Empty;}}catch (Exception ex){// 处理异常Console.WriteLine($"转换 SecureString 出错:{ex.Message}");return string.Empty;}finally{// 清除内存中的敏感数据if (ptr != IntPtr.Zero){Marshal.ZeroFreeGlobalAllocUnicode(ptr);}}}}
}

MainViewModel如下:

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using WPF练习13简单的项目.Helper;
using WPF练习13简单的项目.Model;
using WPF练习13简单的项目.Service;
using WPF练习13简单的项目.View.UserControls;namespace WPF练习13简单的项目.ViewModel
{public class MainViewModel: ObservableObject{private readonly IUserInfo userService;public MainViewModel(){userService = App.Current.Services.GetService<IUserInfo>();CurrentUser = LoginInfoHelper.CurrentUser;WhichUserControl = App.Current.Services.GetService<User>();}private UserInfo currentUser;public UserInfo CurrentUser{get => currentUser;set => SetProperty(ref currentUser, value);}private UserControl whichUserControl;public UserControl WhichUserControl{get => whichUserControl;set => SetProperty(ref whichUserControl, value);}public RelayCommand<string> ToggleCommand{get{return new RelayCommand<string>((str) =>{switch (str){case "用户管理":WhichUserControl = App.Current.Services.GetService<User>();break;case "博客类型":WhichUserControl = App.Current.Services.GetService<BlogType>();break;case "博客管理":WhichUserControl = App.Current.Services.GetService<Post>();break;case "评论管理":WhichUserControl = App.Current.Services.GetService<Comment>();break;default:WhichUserControl = App.Current.Services.GetService<User>();break;}});}}public RelayCommand ClosedCommand{get{return new RelayCommand(() =>{App.Current.Shutdown();});}}}
}

第九步:在Login.XAML和Main.XAML中写对应的前端代码

1.在Dict文件夹中创建LoginDictionary.xaml存放登录窗口的样式

 LoginDictionary.xaml如下:
<Application x:Class="WPF练习13简单的项目.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WPF练习13简单的项目"StartupUri="View/Login.xaml"><Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="Dict/LoginDictionary.xaml" /></ResourceDictionary.MergedDictionaries><Style x:Key="ButtonDefault"TargetType="Button"><Setter Property="FocusVisualStyle"Value="{x:Null}" /><Setter Property="Width"Value="80" /><Setter Property="Height"Value="30" /><Setter Property="Foreground"Value="#ffffff" /><Setter Property="Background"Value="#9e6f55" /><Setter Property="BorderThickness"Value="0" /></Style><Style x:Key="TextBoxDefault"TargetType="TextBox"><Setter Property="Width"Value="150" /><Setter Property="Height"Value="30" /><Setter Property="VerticalContentAlignment"Value="Center" /><Setter Property="Padding"Value="10,0,0,0" /><Setter Property="BorderBrush"Value="#9e6f55" /></Style><Style x:Key="PasswordBoxDefault"TargetType="PasswordBox"><Setter Property="Width"Value="150" /><Setter Property="Height"Value="30" /><Setter Property="VerticalContentAlignment"Value="Center" /><Setter Property="Padding"Value="10,0,0,0" /><Setter Property="BorderBrush"Value="#9e6f55" /></Style></ResourceDictionary></Application.Resources>
</Application>

2.App.XAML文件中存在共同的样式以及存放LoginDictionary.xaml的引用

 <Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="Dict/LoginDictionary.xaml" /></ResourceDictionary.MergedDictionaries><Style x:Key="ButtonDefault"TargetType="Button"><Setter Property="FocusVisualStyle"Value="{x:Null}" /><Setter Property="Width"Value="80" /><Setter Property="Height"Value="30" /><Setter Property="Foreground"Value="#ffffff" /><Setter Property="Background"Value="#9e6f55" /><Setter Property="BorderThickness"Value="0" /></Style><Style x:Key="TextBoxDefault"TargetType="TextBox"><Setter Property="Width"Value="150" /><Setter Property="Height"Value="30" /><Setter Property="VerticalContentAlignment"Value="Center" /><Setter Property="Padding"Value="10,0,0,0" /><Setter Property="BorderBrush"Value="#9e6f55" /></Style><Style x:Key="PasswordBoxDefault"TargetType="PasswordBox"><Setter Property="Width"Value="150" /><Setter Property="Height"Value="30" /><Setter Property="VerticalContentAlignment"Value="Center" /><Setter Property="Padding"Value="10,0,0,0" /><Setter Property="BorderBrush"Value="#9e6f55" /></Style></ResourceDictionary>

3.在Login.XAML文件中创建上下文并创建基本样式 

<Window x:Class="WPF练习13简单的项目.View.Login"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:WPF练习13简单的项目.View"xmlns:vm="clr-namespace:WPF练习13简单的项目.ViewModel"xmlns:i="http://schemas.microsoft.com/xaml/behaviors"d:DataContext="{d:DesignInstance Type=vm:LoginViewModel}"FocusManager.FocusedElement="{Binding ElementName=txtUserName}"mc:Ignorable="d"Title="Login"Height="450"Width="800"><Window.DataContext><vm:LoginViewModel /></Window.DataContext><Grid HorizontalAlignment="Center"VerticalAlignment="Center"><Grid.RowDefinitions><RowDefinition /><RowDefinition /><RowDefinition /></Grid.RowDefinitions><WrapPanel><Label Content="账号:" /><TextBox Name="txtUserName"Style="{StaticResource TextBoxDefault}"Template="{DynamicResource TextBoxTemplate}"Text="{Binding UserName}" /></WrapPanel><WrapPanel Grid.Row="1"Margin="0,10,0,0"><Label Content="密码:" /><PasswordBox Name="PasswordBox"Style="{StaticResource PasswordBoxDefault}"Template="{DynamicResource PasswordBoxTemplate}"><i:Interaction.Triggers><i:EventTrigger EventName="PasswordChanged"><i:InvokeCommandAction Command="{Binding PasswordChangedCommand}"CommandParameter="{Binding ElementName=PasswordBox}" /></i:EventTrigger></i:Interaction.Triggers></PasswordBox></WrapPanel><WrapPanel Grid.Row="2"Margin="0,10,0,0"HorizontalAlignment="Center"><Button Name="btnLogin"Command="{Binding LoginCommand}"CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"Content="登录"IsDefault="True"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /></WrapPanel></Grid>
</Window>

4.在Main.XAML文件中创建上下文并创建基本样式 

<Window x:Class="WPF练习13简单的项目.View.Main"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:WPF练习13简单的项目.View"xmlns:vm="clr-namespace:WPF练习13简单的项目.ViewModel"xmlns:i="http://schemas.microsoft.com/xaml/behaviors"d:DataContext="{d:DesignInstance Type=vm:MainViewModel}"WindowStartupLocation="CenterScreen"mc:Ignorable="d"Title="Main"Height="450"Width="800"><Window.DataContext><vm:MainViewModel /></Window.DataContext><i:Interaction.Triggers><i:EventTrigger EventName="Closed"><i:InvokeCommandAction Command="{Binding ClosedCommand}" /></i:EventTrigger></i:Interaction.Triggers><Grid><Grid.RowDefinitions><RowDefinition Height="60" /><RowDefinition /></Grid.RowDefinitions><Grid Background="#f4eeee"><Grid.ColumnDefinitions><ColumnDefinition /><ColumnDefinition Width="200" /></Grid.ColumnDefinitions><WrapPanel VerticalAlignment="Center"><TextBlock Padding="10,0,0,0"FontSize="20"Text="博客后台管理系统" /></WrapPanel><WrapPanel Grid.Column="1"HorizontalAlignment="Right"VerticalAlignment="Center"><TextBlock VerticalAlignment="Center"Text="当前用户:" /><TextBlock VerticalAlignment="Center"Text="{Binding CurrentUser.UserName}" /><Button Margin="10,0"Command="{Binding ClosedCommand}"Content="退出"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /></WrapPanel></Grid><Grid Grid.Row="1"><Grid.ColumnDefinitions><ColumnDefinition Width="160" /><ColumnDefinition /></Grid.ColumnDefinitions><StackPanel Background="#9e6f55"><Button Width="160"Margin="0,10,0,10"Command="{Binding ToggleCommand}"CommandParameter="用户管理"Content="用户管理"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /><Button Width="160"Margin="0,0,0,10"Command="{Binding ToggleCommand}"CommandParameter="博客类型"Content="博客类型"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /><Button Width="160"Margin="0,0,0,10"Command="{Binding ToggleCommand}"CommandParameter="博客管理"Content="博客管理"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /><Button Width="160"Margin="0,0,0,10"Command="{Binding ToggleCommand}"CommandParameter="评论管理"Content="评论管理"Style="{StaticResource ButtonDefault}"Template="{DynamicResource ButtonTemplate}" /></StackPanel><ContentControl Grid.Column="1"Margin="10"Content="{Binding WhichUserControl}" /></Grid></Grid>
</Window>

效果如下:

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/59514.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

人工智能技术:未来生活的“魔法师”

想象一下&#xff0c;未来的某一天&#xff0c;你醒来时&#xff0c;智能助手已经为你准备好了早餐&#xff0c;你的智能家居系统根据你的心情和日程安排调整了室内的光线和音乐&#xff0c;而你的自动驾驶汽车已经在门口等你。这不是科幻小说&#xff0c;这是人工智能技术为我…

排序(用java实现)

排序 排序的概念及引用排序的概念常见的排序算法 常见排序算法的实现插入排序基本思想&#xff1a;直接插入排序希尔排序(缩小增量排序) 选择排序基本思想&#xff1a;直接选择排序堆排序 交换排序冒泡排序快速排序快速排序的优化快速排序非递归 归并排序基本思想归并排序归并排…

(C++回溯算法)微信小程序“开局托儿所”游戏

问题描述 给定一个矩阵 A ( a i j ) m n \bm A(a_{ij})_{m\times n} A(aij​)mn​&#xff0c;其中 a i j ∈ { 1 , 2 , ⋯ , 9 } a_{ij}\in\{1,2,\cdots,9\} aij​∈{1,2,⋯,9}&#xff0c;且满足 ∑ i 1 m ∑ j 1 n a i j \sum\limits_{i1}^m\sum\limits_{j1}^na_{ij} i…

数字IC后端实现之Innovus Place跑完density爆涨案例分析

下图所示为咱们社区a7core后端训练营学员的floorplan。 数字IC后端实现 | Innovus各个阶段常用命令汇总 该学员跑placement前density是59.467%&#xff0c;但跑完place后density飙升到87.68%。 仔细查看place过程中的log就可以发现Density一路飙升&#xff01; 数字IC后端物…

聊一聊Elasticsearch的索引的分片分配机制

1、什么是分片分配 分片分配是由ES主节点将索引分片移动到ES集群中各个节点上的过程。 该过程尽量保证&#xff0c;同一个索引的分片尽量分配到更多的节点上&#xff0c;以此来达到读写索引的时候可以利用更多硬件资源的效果。 在分配过程当中&#xff0c;也不能将某个主分片…

最详细【Elasticsearch】Elasticsearch Java API + Spring Boot集成 实战入门(基础篇)

Elasticsearch Java API Spring Boot集成 实战入门&#xff08;基础篇&#xff09; 一、初始Elasticseach1、什么是Elasticseach2、Elasticsearch生态2、Elasticsearch结构3、Elasticsearch核心概念4、Elasticsearch 实现全文检索的原理 二、Elasticsearch入门1、入门-环境安装…

文件操作:Xml转Excel

1 添加依赖 Spire.Xls.jar <dependency><groupId>e-iceblue</groupId><artifactId>spire.xls</artifactId><version>5.3.3</version></dependency>2 代码使用 package cctd.controller;import com.spire.xls.FileFormat; im…

物理验证Calibre LVS Debug案例之通过deleteEmptyModule解决LVS问题

上周帮助T12nm A55训练营学员debug一个Calibre LVS问题&#xff0c;小编觉得挺好的一个问题。这个问题之前没有遇到过&#xff0c;今天分享给大家。 数字IC后端先进工艺设计实现之TSMC 12nm 6Track工艺数字IC后端实现重点难点盘点 下图所示为Calibre LVS的报告。从报告中看到…

深度解析阿里的Sentinel

1、前言 这是《Spring Cloud 进阶》专栏的第五篇文章&#xff0c;这篇文章介绍一下阿里开源的流量防卫兵Sentinel&#xff0c;一款非常优秀的开源项目&#xff0c;经过近10年的双十一的考验&#xff0c;非常成熟的一款产品。 文章目录如下&#xff1a; 2、什么是sentinel&…

ReactPress系列—Next.js 的动态路由使用介绍

ReactPress Github项目地址&#xff1a;https://github.com/fecommunity/reactpress 欢迎提出宝贵的建议&#xff0c;感谢Star。 Next.js 的动态路由使用介绍 Next.js 是一个流行的 React 框架&#xff0c;支持服务端渲染、静态站点生成和动态路由等功能&#xff0c;极大地简化…

软件压力测试有多重要?北京软件测试公司有哪些?

软件压力测试是一种基本的质量保证行为&#xff0c;它是每个重要软件测试工作的一部分。压力测试是给软件不断加压&#xff0c;强制其在极限的情况下运行&#xff0c;观察它可以运行到何种程度&#xff0c;从而发现性能缺陷。 在数字化时代&#xff0c;用户对软件性能的要求越…

学习方法该升级了,‌AI时代的弯道超车:【心流学习法】行动与意识合一的巅峰进化

你是否曾感到内心如荒漠般干涸&#xff0c;面对浩瀚的知识海洋&#xff0c;热情逐渐消磨殆尽&#xff1f; 你是否渴望忘却时间的流逝&#xff0c;心无旁骛&#xff0c;与知识展开一场纯粹而深邃的对话&#xff1f; ​在AI时代&#xff0c;智能体处理数据、知识迭代的速率让人…

手边酒店多商户版V2源码独立部署_博纳软云

新版采用laraveluniapp开发&#xff0c;为更多平台小程序开发提供坚实可靠的底层架构基础。后台UI全部重写&#xff0c;兼容手机端管理。 全新架构、会员卡、钟点房、商城、点餐、商户独立管理

机器学习(二)——线性回归模型、多分类学习(附核心思想和Python实现源码)

目录 关于1. 基本形式2. 线性回归2.1 单变量线性回归2.2 多元线性回归2.2 对数线性回归 3. 对数几率回归4. 线性判别分析5. 多分类学习5.1 拆分策略 6. 类别不平衡问题X 案例代码X.1 源码X.2 数据集&#xff08;糖尿病数据集&#xff09;X.3 模型效果 关于 本文是基于西瓜书&a…

跳表原理笔记

课程地址 跳表是一种基于随机化的有序数据结构&#xff0c;它提出是为了赋予有序单链表以 O(logn) 的快速查找和插入的能力 创建 首先在头部创建一个 sentinel 节点&#xff0c;然后在 L1 层采用“抛硬币”的方式来决定 L0 层的指针是否增长到 L1 层 例如上图中&#xff0c;L…

wpf 制作丝滑Flyout浮出侧边栏Demo (Mahapps UI框架)

Flyout 属性 CloseButtonVisibility: 设置为 Collapsed&#xff0c;意味着关闭按钮不可见。TitleVisibility: 设置为 Collapsed&#xff0c;意味着标题不可见。IsPinned: 设置为 True&#xff0c;意味着这个 Flyout 会固定住&#xff0c;不会自动关闭。Opacity: 设置为 1&…

MySQL记录锁、间隙锁、临键锁(Next-Key Locks)详解

行级锁&#xff0c;每次操作锁住对应的行数据。锁定粒度最小&#xff0c;发生锁冲突的概率最低&#xff0c;并发度最高。 应用在InnoDB存储引擎中。InnoDB的数据是基于索引组织的&#xff0c;行锁是通过对索引上的索引项加锁来实现的&#xff0c;而不是对记录加的锁。 对于行…

GeoSever发布图层(保姆姬)

发布服务的具体步骤。 1. 安装 GeoServer 下载 GeoServer 安装包&#xff1a;GeoServer 官网按照安装说明进行安装&#xff0c;可以选择 Windows、Linux 或其他平台。 2. 启动 GeoServer 启动 GeoServer 通常通过访问 http://localhost:8080/geoserver 进行。默认用户名和密…

交易所开发:构建安全、高效、可靠的数字资产交易平台

随着数字资产的不断发展&#xff0c;数字货币交易所作为连接数字资产与现实世界的重要桥梁&#xff0c;逐渐成为全球金融市场的核心组成部分。无论是比特币、以太坊等主流加密货币&#xff0c;还是各种基于区块链的资产&#xff0c;都需要通过交易所进行交换和流通。因此&#…

了解分布式数据库系统中的CAP定理

在分布式数据库系统的设计和实现中&#xff0c;CAP定理是一个至关重要的概念。CAP定理&#xff0c;全称为一致性&#xff08;Consistency&#xff09;、可用性&#xff08;Availability&#xff09;和分区容忍性&#xff08;Partition tolerance&#xff09;定理&#xff0c;由…