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.xdnf.cn/news/4018.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

多模态PaliGemma——Google推出的基于SigLIP和Gemma的视觉语言模型

前言 本文怎么来的呢&#xff1f;其实很简单&#xff0c;源于上一篇文章《π0——用于通用机器人控制的流匹配VLA模型&#xff1a;一套框架控制7种机械臂(改造了PaliGemma和ACT的3B模型)》中的π0用到了PaliGemma 故本文便来解读下这个PaliGemma 第一部分 PaliGemma 1.1 Pal…

微服务day03

导入黑马商城项目 创建Mysql服务 由于已有相关项目则要关闭DockerComponent中的已开启的项目 [rootserver02 ~]# docker compose down WARN[0000] /root/docker-compose.yml: version is obsolete [] Running 4/4✔ Container nginx Removed …

IAPP仿源码大师主界面UI

仿源码大师首页主界面的布局 首页&#xff0c;分类&#xff0c;需求&#xff0c;我的 就只有这几个界面内容而已 资源静态 没有任何动画和功能 纯UI布局 纯UI布局 https://pan.baidu.com/s/1Hc5nWQCZ_ckQlXXV82OYpA?pwd7826 https://caiyun.139.com/m/i?2i2MoYbkdze41 来源…

mmpretrainmmdetection环境配置

mmpretrain&mmdetection环境配置 适用于cuda11.3torch12.1的mmpretrain&mmdetection环境配置&#xff1a; 第一步&#xff1a;根据官网说明&#xff0c;找到对应cuda版本的torch&#xff0c;安装好torch&#xff1a; pip install torch1.12.1cu113 torchvision0.13.…

【数据湖及大数据方案】数据湖建设方案|数据源|数据流|元数据|数据仓库|指标池|数据清洗

建设大数据湖一体化平台旨在应对数据分散、管理混乱及利用低效等挑战。通过集中存储与管理跨平台数据&#xff0c;打破信息孤岛&#xff0c;实现数据资产的高效整合与利用。该平台强化数据标准、质量控制、开发运维及安全保障&#xff0c;提升数据治理成熟度。此外&#xff0c;…

搭建企业私有云 只需一台设备 融合计算、存储与K8s

Infortrend老牌存储厂商推出 KS 企业私有云产品&#xff0c;将计算节点、存储与Kubernetes整合在一套系统中&#xff0c;为企业提供高效稳定的专属本地私有云平台。 KS 同时内置 Kubernetes 平台和虚拟机管理程序&#xff0c;既能运行云原生容器化应用程序&#xff0c;例如大数…

[Redis] Redis主从复制模式

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…

计算机毕业设计Hadoop+PySpark深度学习游戏推荐系统 游戏可视化 游戏数据分析 游戏爬虫 Scrapy 机器学习 人工智能 大数据毕设

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

iOS SmartCodable 替换 HandyJSON 适配记录

前言 HandyJSON群里说建议不要再使用HandyJSON&#xff0c;我最终选择了SmartCodable 来替换&#xff0c;原因如下&#xff1a; 首先按照 SmartCodable 官方教程替换 大概要替换的内容如图&#xff1a; 详细的替换教程请前往&#xff1a;使用SmartCodable 平替 HandyJSON …

16、论文阅读:Mamba YOLO:用于目标检测的基于 SSM 的 YOLO

Mamba YOLO: SSMs-Based YOLO For Object Detection 总结前言感受野为什么Transformer 的结构被引入&#xff0c;显著扩展了模型的感受野&#xff1f;状态空间模型SSM 介绍相关工作实时目标检测端到端目标检测器视觉状态空间模型 方法预处理整体架构ODSS BlockLocalSpatial Blo…

微信小程序 uniapp+vue老年人身体监测系统 acyux

文章目录 项目介绍具体实现截图技术介绍mvc设计模式小程序框架以及目录结构介绍错误处理和异常处理java类核心代码部分展示详细视频演示源码获取 项目介绍 过此方式促进老年人辅助程序信息流动和数据传输效率&#xff0c;提供一个内容丰富、功能多样、易于操作的老年人辅助程序…

Intellij IDE报错:[Information:java:javacTask:源发行版8需要目标发行版1.8]

Intellij IDE报错:[Information:java:javacTask:源发行版8需要目标发行版1.8] 处理方法 File->Settings->Build,execution,Deployment->Compiler->Java Compiler 进入该目录下&#xff0c;修改Per-module bytecode version&#xff0c;将该项目修改为8 合理的创…

Pr 沉浸式视频 - 自动 VR 属性

自动 VR 属性 Auto VR Properties是所有 VR 视频效果和视频过渡效果的通用选项。 默认勾选。此选项使效果自动适应 VR 素材的属性&#xff0c;确保在 360 全景环境中无缝显示。 当处理 VR/360 素材时&#xff0c;保持勾选以避免接缝。 当处理非 VR 素材或需要手动设置 VR 属性时…

[项目] C++基于多设计模式下的同步异步日志系统

[项目] C基于多设计模式下的同步&异步日志系统 文章目录 [项目] C基于多设计模式下的同步&异步日志系统日志系统1、项目介绍2、开发环境3、核心技术4、日志系统介绍4.1 日志系统的价值4.2 日志系统技术实现4.2.1 同步写日志4.2.2 异步写日志 5、相关技术知识5.1 不定参…

ubuntu下使用pocketsphinx进行语音识别

文章目录 前言一、pocketsphinx的介绍二、ubuntu下编译三、使用示例1.模型选择2.代码示例3.自定义字典 四、交叉编译总结 前言 由于工作需要语音识别的功能&#xff0c;环境是在linux arm版上&#xff0c;所以想先在ubuntu上跑起来看一看&#xff0c;就找了一下语音识别的开源…

C语言原码、反码和补码的详解

C语言原码、反码和补码的详解 放在最前面的1、前言正数的原码、反码和补码负数的原码、反码和补码 2、整数的原码&#xff08;2.1&#xff09;原码的定义&#xff08;2.2&#xff09;计算原码 3、整数的反码&#xff08;3.1&#xff09;反码的定义&#xff08;3.2&#xff09;计…

知识课堂——高匿ip在不同业务中的重要作用

大家好&#xff01;今天我们来看看高匿ip在不同业务中都能起到什么样的重要作用。第一个会用到的地方就是网络数据采集&#xff0c;也被称为网络爬虫&#xff0c;在是许多企业和机构获取大量数据的重要手段。例如市场调研公司帮助企业制定市场策略就需要收集各个行业的产品价格…

【青牛科技】GC8548替代LV8548/ONSEMI在摇头机、舞台灯、打印机和白色家电等产品上的应用分析

引言 在现代电子设备中&#xff0c;控制芯片的选择对产品的性能和可靠性至关重要。摇头机、舞台灯、打印机和白色家电等领域对芯片的要求日益增加&#xff0c;传统上多采用LV8548/ONSEMI等国际品牌的芯片。然而&#xff0c;随着国内半导体技术的不断进步&#xff0c;芯麦GC854…

【C/C++】字符/字符串函数(0)——由ctype.h提供

零.导言 众所周知&#xff0c;C语言的字符有许多不同的类型&#xff0c;如&#xff1a;数字&#xff0c;字母&#xff0c;标点符号等等等等。 今天&#xff0c;我就给大家讲解一下用于实现字符分类的函数——字符分类函数。 一.什么是字符分类函数&#xff1f; 即实现字符分类的…

专业网页设计服务重要是什么

当在搜索引擎中键入“网页设计”&#xff0c;您将获得超过2000万个相关结果。在如此众多的网站制作公司中&#xff0c;应该如何做出明智的选择呢&#xff1f;首先&#xff0c;让我们深入探讨一下网页设计的重要性。网站设计需要综合各种不同领域的专业知识&#xff0c;它是一个…