原因:
最近要面试一家公司,公司有对WPF架构的要求,然后就开始自学了。
功能描述:
加载所有学生信息、名字筛选学生信息、重置筛选、新增学生信息、修改学生信息、删除学生信息。
窗体样式:
操作步骤:
一、引用文件包:(进去管理NuGet程序包,引入EF Core所需的三个包)
二、创建实体模型类:(这里以Student实体模型类为例)
public class Student
{
//学生学号
public int StudentId { get; set; }
//学生姓名
public string StudentName { get; set; }
//学生性别
public string StudentSex { get; set; }
//学生年龄
public int StudentAge { get; set; }
//学生住址
public string StudentAddress { get; set; }
}
三、创建数据库上下文类:(必须以Context结尾)
public class StudentContext : DbContext
{
//数据库表格
public DbSet<Student> Students { get; set; }
//重构Context方法
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//数据库连接语句
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=StudentDB;Integrated Security = true");
}
}
四、使用NuGet包管理命令生成数据库和表:
先输入 Add-Migration Name 命令(Name可以自定义命名),等到数据库创建成功后,
再输入 Update-Database 命令。
成功创建后会有生成的数据库生成文件:
五、创建StudnetDAL类:
public class StudentDAL
{
//获取学生信息
public static List<Student> Select()
{
StudentContext db = new StudentContext();
return db.Students.ToList();
}
//新增学生信息
public static bool Insert(Student student)
{
StudentContext db = new StudentContext();
db.Students.Add(student);
return db.SaveChanges() > 0;
}
//修改学生信息
public static bool Update(Student student)
{
StudentContext db = new StudentContext();
db.Entry(student).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
return db.SaveChanges() > 0;
}
//删除学生信息
public static bool Delete(Student student)
{
StudentContext db = new StudentContext();
var studnet1 = db.Students.Find(student.StudentId);
db.Students.Remove(studnet1);
return db.SaveChanges() > 0;
}
//根据学号获取学生信息
public static Student GetStudent(int StudetId)
{
StudentContext db = new StudentContext();
return db.Students.SingleOrDefault(s => s.StudentId == StudetId);
}
}
六、编辑XAML主窗体:(前面的东西都是.Net Core的东西,现在才和WPF搭边)
<Window x:Class="WefApp7._17.MainWindow"
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:WefApp7._17"
mc:Ignorable="d"
Title="学生信息" Height="450" Width="800">
<Grid>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="关键词" VerticalAlignment="Center" Margin="10 -380 0 0"/>
<TextBox Width="200" Height="25" Name="Search" Margin="10 -380 0 0"></TextBox>
<Button Content="查找" Width="70" Height="25" Margin="10 -380 0 0" Name="Select" Click="Select_Click" ></Button>
<Button Content="重置" Width="70" Height="25" Margin="10 -380 0 0" Click="Reset_Click"></Button>
<Button Content="新增" Width="70" Height="25" Margin="10 -380 0 0" Click="Add_Click" ></Button>
</StackPanel>
<DataGrid ItemsSource="{Binding}" ColumnWidth="*" CanUserAddRows="False" CanUserSortColumns="False" AutoGenerateColumns="False" Margin="0 60 0 0" >
<DataGrid.Columns>
<DataGridTextColumn Header="学号" Binding="{Binding StudentId}"/>
<DataGridTextColumn Header="姓名" Binding="{Binding StudentName}"/>
<DataGridTextColumn Header="性别" Binding="{Binding StudentSex}"/>
<DataGridTextColumn Header="年龄" Binding="{Binding StudentAge}"/>
<DataGridTextColumn Header="地址" Binding="{Binding StudentAddress}"/>
<DataGridTemplateColumn Header="操作">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="修改" Width="60" Height="25" Background="White" Foreground="Black" Tag="{Binding StudentId}" Click="Edit_Click"/>
<Button Content="删除" Width="60" Height="25" Background="Red" Foreground="White"
Tag="{Binding StudentId}" Click="Delete_Click" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
七、主窗体后台代码:(由于没有用到MVVM,所以感觉很笨)
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//加载所有数据
this.DataContext = StudentDAL.Select();
InitializeComponent();
}
//点击搜索按钮
private void Select_Click(object sender, RoutedEventArgs e)
{
//获取搜索关键词
var search = (this.FindName("Search") as TextBox).Text;
//获取学生信息
var list = StudentDAL.Select();
//筛选学生信息
if(!string.IsNullOrEmpty(search))
{
list = list.Where(s => s.StudentName.Contains(search)).ToList();
}
//绑定筛选后的学生信息
this.DataContext = list;
}
//点击重置按钮
private void Reset_Click(object sender, RoutedEventArgs e)
{
//重置窗体信息
(this.FindName("Search") as TextBox).Text = "";
this.DataContext = StudentDAL.Select();
}
//点击修改按钮
private void Edit_Click(object sender, RoutedEventArgs e)
{
//获取学生学号
int studetnId = Convert.ToInt32(((Button)sender).Tag);
//获取学生信息
var student = StudentDAL.GetStudent(studetnId);
if (student != null)
{
//调用有参构造方法打开窗体
AddStudent addStudent = new AddStudent(student);
addStudent.ShowDialog();
//刷新界面信息
this.DataContext = StudentDAL.Select();
}
}
//点击新增按钮
private void Add_Click(object sender, RoutedEventArgs e)
{
//新增学生信息
AddStudent addStudent = new AddStudent();
//打开页面
addStudent.ShowDialog();
//刷新学生信息
this.DataContext = StudentDAL.Select();
}
//点击删除按钮
private void Delete_Click(object sender, RoutedEventArgs e)
{
//学生学号
int studetnId = Convert.ToInt32(((Button)sender).Tag);
//获取对应的学生信息
var student = StudentDAL.GetStudent(studetnId);
//删除警告
var result = MessageBox.Show($"当真要删除‘{student.StudentName}’的信息?","删除警告",MessageBoxButton.OKCancel,MessageBoxImage.Question);
//执行删除
if (result == MessageBoxResult.OK)
{
//删除学生信息
StudentDAL.Delete(student);
}
//刷新数据
this.DataContext = StudentDAL.Select();
}
}
八、学生信息处理窗体:
<Window x:Class="WefApp7._17.Views.AddStudent"
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:WefApp7._17.Views"
mc:Ignorable="d" WindowStyle="None" AllowsTransparency="True" WindowStartupLocation="CenterScreen"
Title="AddStudent" Height="400" Width="400" Loaded="AddStudent_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock FontSize="30" FontWeight="Bold" Text="学生信息处理" VerticalAlignment="Center"></TextBlock>
<StackPanel Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="学号" VerticalAlignment="Center"></TextBlock>
<TextBox Name="txtStudentId" IsReadOnly="True" Width="200"></TextBox>
<TextBlock Text="姓名" VerticalAlignment="Center"></TextBlock>
<TextBox Name="txtStudentName" Width="200"></TextBox>
<TextBlock Text="性别" VerticalAlignment="Center"></TextBlock>
<StackPanel Orientation="Horizontal">
<RadioButton Name="RadMan" Content="男" />
<RadioButton Name="RadWoman" Margin="10 0 0 0" Content="女" />
</StackPanel>
<TextBlock Text="年龄" VerticalAlignment="Center"></TextBlock>
<TextBox Name="txtStudentAge" Width="200"></TextBox>
<TextBlock Text="家庭住址" VerticalAlignment="Center"></TextBlock>
<TextBox Name="txtStudentAddress" Width="200"></TextBox>
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Width="70" Height="25" Content="确定" Click="btnSave_Click"></Button>
<Button Width="70" Height="25" Margin="10 0 10 0" Content="取消" Click="btnCancel_Click"></Button>
</StackPanel>
</Grid>
</Window>
九、学生信息处理窗体后台代码:
/// <summary>
/// AddStudent.xaml 的交互逻辑
/// </summary>
public partial class AddStudent : Window
{
//学生信息
public Model.Student Studnet = new Model.Student();
/// <summary>
/// 有学生信息参数的构造方法
/// </summary>
/// <param name="student"></param>
public AddStudent(Model.Student student)
{
//获取学生信息
Studnet = student;
InitializeComponent();
}
/// <summary>
/// 没有参数的构造方法
/// </summary>
public AddStudent()
{
InitializeComponent();
}
//学生信息页面窗体加载事件
private void AddStudent_Loaded(object sender, RoutedEventArgs e)
{
//根据是否有学号,判断是 新增学生信息 还是 修改学生信息
if (Studnet.StudentId > 0)
{
//修改时绑定学生信息
(this.FindName("txtStudentId") as TextBox).Text = Studnet.StudentId.ToString();
(this.FindName("txtStudentName") as TextBox).Text = Studnet.StudentName;
if (Studnet.StudentSex == "男")
{
(this.FindName("RadMan") as RadioButton).IsChecked = true;
}
else if (Studnet.StudentSex == "女")
{
(this.FindName("RadWoman") as RadioButton).IsChecked = true;
}
(this.FindName("txtStudentAge") as TextBox).Text = Studnet.StudentAge.ToString();
(this.FindName("txtStudentAddress") as TextBox).Text = Studnet.StudentAddress.ToString();
}
}
//点击确定按钮
private void btnSave_Click(object sender, RoutedEventArgs e)
{
//获取文本内的学生信息
Student theStudnet = new Student()
{
StudentName = (this.FindName("txtStudentName") as TextBox).Text,
StudentSex = (this.FindName("RadMan") as RadioButton).IsChecked == true ? "男" : "女",
StudentAge = Convert.ToInt32((this.FindName("txtStudentAge") as TextBox).Text),
StudentAddress = (this.FindName("txtStudentAddress") as TextBox).Text
};
//根据学号判断是 执行修改 还是 执行新增
if (Studnet.StudentId > 0)
{
//修改学生信息
theStudnet.StudentId = Studnet.StudentId;
StudentDAL.Update(theStudnet);
}
else
{
//新增学生信息
StudentDAL.Insert(theStudnet);
}
//结束弹窗
this.DialogResult = true;
}
//点击取消按钮
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
//结束弹窗
this.DialogResult = false;
}
}