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.rhkb.cn/news/466332.html

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

相关文章

基于python多准则决策分析的汽车推荐算法设计与实现

摘要 随着汽车市场的快速发展和消费者需求的多样化&#xff0c;汽车选择变得愈加复杂。为了帮助消费者在众多汽车选项中做出明智的决策&#xff0c;基于多准则决策分析&#xff08;MCDA&#xff09;的汽车推荐算法应运而生。本研究旨在设计和实现一种基于 Python 的汽车推荐系…

xftp连接中不成功 + sudo vim 修改sshd_config不成功的解决方法

我们使用sudo vim不成功&#xff0c;但是我们使用sudo su就可以 了&#xff01; root用户权利更大&#xff01; 喵的&#xff0c;终于成功了&#xff0c;一个xftp连接半天不成功。&#xff08;添加上面的内容就可以连接成功了↑&#xff09;

vue:Transition

1. Transition 1. 基本用法 <Transition> 是Vue 提供的 “内置组件动画组件”&#xff0c;与一般的CSS过渡动画不同的是&#xff0c;它通过在特点时刻给元素或组件增加、移除类名来实现——在一个元素或组件进入和离开 DOM 时应用过渡动画。 下面是一个基本用法&#…

Python 中的字符串匹配算法

在 Python 中&#xff0c;字符串匹配算法用于在一个字符串中寻找一个子串的出现位置&#xff0c;这是许多文本处理任务的核心。下面我将介绍几种常用的字符串匹配算法以及它们在 Python 中的实现方式。 1、问题背景 在 Python 中&#xff0c;字符串匹配是一个非常重要的操作&a…

配置本地策略路由示例

组网需求 RouterA与RouterB间有两条链路相连。 用户希望实现本机下发的不同长度的报文通过不同的下一跳地址进行转发&#xff0c;其中&#xff1a; 长度为64&#xff5e;1400字节的报文设置192.168.1.2作为下一跳地址。长度为1401&#xff5e;1500字节的报文设置192.168.2.2…

【大数据学习 | kafka高级部分】文件清除原理

2. 两种文件清除策略 kafka数据并不是为了做大量存储使用的&#xff0c;主要的功能是在流式计算中进行数据的流转&#xff0c;所以kafka中的数据并不做长期存储&#xff0c;默认存储时间为7天 那么问题来了&#xff0c;kafka中的数据是如何进行删除的呢&#xff1f; 在Kafka…

推荐一款基于Flash的交互式园林设计工具:Garden Planner

Garden Planner是一款由Artifact Interactive开发的基于Flash的交互式园林设计工具。它允许用户以拖放的方式安排植物、树木、建筑物和各种对象&#xff0c;使园林规划变得简单直观。此外&#xff0c;Garden Planner提供工具来快速创建铺路、路径和围栏&#xff0c;帮助用户设计…

微信小程序开发,诗词鉴赏app,诗词推荐实现(二)

微信小程序开发&#xff0c;诗词鉴赏app&#xff08;一&#xff09;&#xff1a; https://blog.csdn.net/jky_yihuangxing/article/details/143501681微信小程序开发&#xff0c;诗词鉴赏app&#xff0c;诗词推荐实现&#xff08;二&#xff09;:https://blog.csdn.net/jky_yih…

关于诊断中的各种时间参数

前言&#xff1a; 因为不会转载&#xff0c;故在这里贴出原文连接&#xff0c;写的非常好&#xff01;条理清晰&#xff0c;一遍看懂king110108 原文链接&#xff1a;UDS之时间参数总结篇_uds时间参数-CSDN博客 以下内容是我自己对这篇文章的一些备注和理解&#xff0c;以及从测…

技术干货|HyperMesh CFD功能详解:虚拟风洞 Part 2

在上期 Part 1文章中&#xff0c;我们介绍了从 v2023 版本开始&#xff0c;虚拟风洞VWT&#xff08;Virtual Wind Tunnel&#xff09;模块合并到HyperMesh CFD中。用户在VWT模块中完成LBM求解器ultraFluidX的前处理设置&#xff0c;导出参数文件XML和模型文件STL&#xff0c;并…

H7-TOOL的CAN/CANFD助手增加帧发送成功标识支持, 继续加强完善功能细节

2.27版本固件正式携带此功能&#xff0c;包括之前做的负载率检测和错误信息展示也将集成到这个版本固件中。 对于接收&#xff0c;我们可以直接看到效果&#xff0c;而发送不行&#xff0c;所以打算在发送的地方展示下发送成功标识。CAN发送不像串口&#xff0c;需要等待应答后…

mysql5安装

1.下载安装包 https://downloads.mysql.com/archives/community/ mysql-5.7.44-1.el7.x86_64.rpm-bundle.tar tar -xvf mysql-5.7.44-1.el7.x86_64.rpm-bundle.tar2.安装依赖 yum -y install perl yum -y install net-tools yum install numactl libaio libaio-devel -y也可…

大模型应用编排工具Dify二开之工具和模型页面改造

1.前言 简要介绍下 dify&#xff1a; ​ 一款可以对接市面上主流大模型的任务编排工具&#xff0c;可以通过拖拽形式进行编排形成解决某些业务场景的大模型应用。 背景信息&#xff1a; ​ 环境&#xff1a;dify-0.8.3、docker-21 ​ 最近笔者在做 dify的私有化部署和二次…

开放寻址法、链式哈希数据结构详细解读

一、开放寻址法&#xff08;Open Addressing&#xff09; 1. 定义 开放寻址法是一种哈希冲突解决策略&#xff0c;所有元素都存储在哈希表中。当发生冲突时&#xff0c;即两个键计算出的哈希值相同时&#xff0c;会按照一定的探查序列查找下一个可用的位置来存储新元素。 2.…

并查集(基础学习与应用)

并查集 基本原理&#xff1a; 对于多个集合&#xff0c;每个集合中的多个元素用一颗树的形式表示&#xff0c;根节点的编号即为整个集合的编号&#xff0c;每个树上节点存储其父节点&#xff0c;使得当前集合的每个子节点都可以通过对父节点的询问来找到根节点&#xff0c;根…

基于 Encoder-only 架构的大语言模型

基于 Encoder-only 架构的大语言模型 Encoder-only 架构 Encoder-only 架构凭借着其独特的双向编码模型在自然语言处理任务中表现出色&#xff0c;尤其是在各类需要深入理解输入文本的任务中。 核心特点&#xff1a;双向编码模型&#xff0c;能够捕捉全面的上下文信息。 En…

sql数据库-DQL-条件查询

条件查询 SELECT 字段列表 FROM 表名 WHERE 条件列表; 条件列表 比较运算符功能> 大于>大于等于 < 小于<小于等于等于!不等于between...and...某个范围之间&#xff08;闭区间&#xff09;IN(...)在in之后的列表中的值&#xff0c;多选一LIKE 通…

Android CCodec Codec2 (二十)C2Buffer与Codec2Buffer

在阅读Codec2框架代码时&#xff0c;我们可能会发现好几个名称中都带有“buffer”的类&#xff0c;如MediaCodecBuffer、ABuffer、CCodecBuffers、Codec2Buffer以及C2Buffer。它们分别是什么&#xff1f;各自承担着什么功能&#xff1f;它们之间有何联系&#xff1f;本文将围绕…

WPF怎么通过RestSharp向后端发请求

1.下载RestSharpNuGet包 2.请求类和响应类 public class ApiRequest {/// <summary>/// 请求地址/// </summary>public string Route { get; set; }/// <summary>/// 请求方式/// </summary>public Method Method { get; set; }/// <summary>//…

SQL Server 日志记录

SQL Server是一个关系数据库管理系统&#xff08;RDBMS&#xff09;&#xff0c;旨在有效地存储、组织、检索和操作大量结构化数据。SQL Server日志是监控数据库活动、排查问题和确保数据一致性的基础&#xff0c;这些日志记录了SQL Server实例中发生的事件的时间顺序。它们充当…