- папка "Views"
MainWindow.xaml
<Window x:Class="_20200203_mvvm_gyudong.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:_20200203_mvvm_gyudong"
mc:Ignorable="d"
Title="MVVM in WPF - Gyudong Kim" Height="450" Width="800">
<Border Padding="10">
<Grid Name ="Grid" HorizontalAlignment="Left" Height="400" VerticalAlignment="Center" Width="770">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="BtnRead" Content="Read" Grid.Row="0" Grid.Column="1" Margin="0 10 0 10" Click="BtnRead_Click"/>
<Button Name="BtnInsert" Content="Insert" Grid.Row="1" Grid.Column="1" Margin="0 10 0 10" Click="BtnInsert_Click"/>
<Button Name="BtnUpdate" Content="Update" Grid.Row="2" Grid.Column="1" Margin="0 10 0 10" Click="BtnUpdate_Click"/>
<Button Name="BtnDelete" Content="Delete" Grid.Row="3" Grid.Column="1" Margin="0 10 0 10" Click="BtnDelete_Click"/>
<DataGrid Name="datagridStudent" Grid.RowSpan="4" Width="640" Height="390" Margin="0 10 0 10"
AutoGenerateColumns="False" CanUserResizeRows="False" ItemsSource="{Binding Path=tblStudent}">
<DataGrid.Columns>
<DataGridTextColumn Header="grade" Binding="{Binding Path=grade}" Width="120"/>
<DataGridTextColumn Header="cclass" Binding="{Binding Path=cclass}" Width="120"/>
<DataGridTextColumn Header="no" Binding="{Binding Path=no}" Width="150"/>
<DataGridTextColumn Header="name" Binding="{Binding Path=name}" Width="120"/>
<DataGridTextColumn Header="score" Binding="{Binding Path=score}" Width="120"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Border>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using _20200203_mvvm_gyudong.ViewModels;
namespace _20200203_mvvm_gyudong
{
public partial class MainWindow : Window
{
StudentViewModel st = new StudentViewModel();
public MainWindow()
{
InitializeComponent();
}
private void BtnRead_Click(object sender, RoutedEventArgs e)
{
st.SelectView();
}
private void BtnInsert_Click(object sender, RoutedEventArgs e)
{
string insertQuery = "INSERT INTO student VALUES (@grade, @cclass, @no, @name, @score)";
st.ExecuteQuery(insertQuery);
}
private void BtnUpdate_Click(object sender, RoutedEventArgs e)
{
string updateQuery = "UPDATE student SET grade = @grade, cclass = @cclass, no = @no, name = @name, score = @score WHERE grade = @grade";
st.ExecuteQuery(updateQuery);
}
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
string deleteQuery = "DELETE FROM student WHERE grade = @grade";
st.ExecuteQuery(deleteQuery);
}
}
}
папка "Модели"
Student.cs
namespace _20200203_mvvm_gyudong.Models
{
public class Student
{
public int grade { get; set; }
public int cclass { get; set; }
public int no { get; set; }
public string name { get; set; }
public string score { get; set; }
}
}
папка "ViewModels"
StudentViewModel.cs
using System;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
using System.Windows;
using _20200203_mvvm_gyudong.Models;
using _20200203_mvvm_gyudong.Properties;
namespace _20200203_mvvm_gyudong.ViewModels
{
public class StudentViewModel
{
MySqlConnection conn = new MySqlConnection("Server=localhost;userid=root;password=111111;Database=ACK");
MySqlCommand cmd;
MySqlDataAdapter adapter;
DataSet ds;
Student std = new Student();
public void OpenConn()
{
if (conn.State == ConnectionState.Closed) { conn.Open(); }
}
public void CloseConn()
{
if (conn.State == ConnectionState.Open) { conn.Close(); }
}
public void SelectView()
{
try
{
conn.Open();
cmd = new MySqlCommand("Select * from student", conn);
adapter = new MySqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "tblStudent");
datagridStudent.DataContext = ds; // How to bind datagrid..?
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
}
public void ExecuteQuery(string query)
{
try
{
OpenConn();
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("@grade", MySqlDbType.Int32).Value = std.grade; // x
cmd.Parameters.Add("@cclass", MySqlDbType.Int32).Value = std.cclass; // x
cmd.Parameters.Add("@no", MySqlDbType.Int64).Value = std.no; // x
cmd.Parameters.Add("@name", MySqlDbType.VarChar, 100).Value = std.name; // x
cmd.Parameters.Add("@score", MySqlDbType.VarChar, 20).Value = std.score; // x
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
CloseConn();
}
}
}
}
Это мой второй вопрос.
I хотите, чтобы CRUD-сетка данных в приложении WPF была реализована в виде MVVM.
Как исправить код?
(Честно говоря, я не очень хорошо понимаю шаблон MVVM.)
Спасибо за вашу доброту.