WPF+SqlSugar+MVVM实现增删改查

1、新建一个WPF应用(NET Framework)

2、安装SqlSugar NuGet包

3、在SqlSugar4.x下载代码生成器:https://www.donet5.com/Doc/8/1137

4、在WPF中新建三个文件夹 Models 主要放实体类、Views 主要放窗体、ViewModels 主要是View逻辑的实现

5、把生成的实体类放到Models文件夹内,在ViewModels 新建一个类DelegateCommands.cs

切记在实体类的加上
public object Clone()
{
return (Object)this.MemberwiseClone();
}

public class DelegateCommands : ICommand
{
//当命令可执行状态发生改变时,应当被激发
public event EventHandler CanExecuteChanged;

    public Action<object> ExecuteCommand = null;

    public Func<object, bool> CanExecuteCommand = null;
    /// <summary>
    /// 用于判断命令是否可以执行
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        if (CanExecuteCommand !=null)
        {
            return CanExecuteCommand(parameter);
        }
        else
        {
            return true;
        }
    }
    /// <summary>
    /// 命令执行
    /// </summary>
    /// <param name="parameter"></param>
    public void Execute(object parameter)
    {
        if (ExecuteCommand !=null)
        {
            ExecuteCommand(parameter);
        }
    }

6、ViewModel新建UserViewModel.cs
public class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}

    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
    {
        //数据库配置
        ConnectionString = "Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=123456",

        DbType = DbType.SqlServer,//设置数据库类型

        IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放

        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息

    });


    private ObservableCollection<Users> userList;
    /// <summary>
    /// 用户集合
    /// </summary>
    public ObservableCollection<Users> UserList
    {
        get
        {
            if (userList == null)
            {
                userList = new ObservableCollection<Users>();
                //设置数据源 //也可以直接写查询
                userList = new ShowDataViewModel().GetUsers();
            }
            return userList;               
        }
        set {
            if (userList == null)
            {
                userList = new ObservableCollection<Users>();
            }
            userList = value;
            OnPropertyChanged("UserList");
        }
    }
    public Users selectUser;
    /// <summary>
    /// 被选中的用户
    /// </summary>
    public Users SelectUser
    {
        get
        {
            if (selectUser == null)
            {
                selectUser = new Users();

            }
            return selectUser;
        }
        set
        {
            if (selectUser == null)
            {
                selectUser = new Users();
            }
            selectUser = value; OnPropertyChanged("SelectUser");
        }
    }
    /// <summary>
    /// 注册命令
    /// </summary>
    private void RegisterCommands()
    {
        AddCommand = new DelegateCommands();
        AddCommand.ExecuteCommand = new Action<object>(AddUser);
        UpdateCommand = new DelegateCommands();
        UpdateCommand.ExecuteCommand = new Action<object>(UpdateUser);
        DeleteCommand = new DelegateCommands();
        DeleteCommand.ExecuteCommand = new Action<object>(DeleteUser);
        SelectionCommand = new DelegateCommands();
        SelectionCommand.ExecuteCommand = new Action<object>(SelectionUser);
    }
    public UserViewModel()
    {
        RegisterCommands();
    }
    /// <summary>
    /// 显示提示信息
    /// </summary>
    /// <param name="txt"></param>
    public void MsgShow(string txt)
    {
        System.Windows.MessageBox.Show(txt);
        //删除后清空选择用户
        SelectUser = null;
    }
    #region 注册命令
    /// <summary>
    /// 新增用户
    /// </summary>
    public DelegateCommands AddCommand { get; set; }
    /// <summary>
    /// 更新用户
    /// </summary>
    public DelegateCommands UpdateCommand { get; set; }
    /// <summary>
    /// 删除用户
    /// </summary>
    public DelegateCommands DeleteCommand { get; set; }
    /// <summary>
    /// 选择用户
    /// </summary>
    public DelegateCommands SelectionCommand { get; set; }
    public void AddUser(object parameter)
    {
        Users us = new Users();
        us.U_Name = SelectUser.U_Name;
        us.U_Age = SelectUser.U_Age;
        us.U_Sex = SelectUser.U_Sex;
        us.U_Tel = SelectUser.U_Tel;
        us.U_Pwd = "123";
        us.D_ID = 1;
        var t3 = db.Insertable(us).ExecuteReturnEntity();
        MsgShow("用户编号:" + t3.U_ID + "\n新增成功!");
        UserList = new ShowDataViewModel().GetUsers();
    }
    public void UpdateUser(object parameter)
    {
        if (SelectUser.U_ID < 1)
        {
            MsgShow("请选择修改项!");
            return;
        }
        //查找需要修改的对象
        Users user = UserList.Where(a => a.U_ID == SelectUser.U_ID).SingleOrDefault();
        //查找需要修改的对象索引
        int index = UserList.IndexOf(user);
        //使数据的复制变为深复制,需要实现ICloneable接口
        var t1 = db.Updateable((Users)SelectUser.Clone()).ExecuteCommand(); //这种方式会以主键为条件
        MsgShow("用户编号:" + SelectUser.U_ID + "\n修改成功!");
        UserList = new ShowDataViewModel().GetUsers();
    }
    public void DeleteUser(object parameter)
    {
        if (SelectUser.U_ID < 1)
        {
            MsgShow("请选择修改项!");
            return;
        }
        Users user = UserList.Where(a => a.U_ID == SelectUser.U_ID).SingleOrDefault();
        var t0 = db.Deleteable<Users>().Where(u => u.U_ID == user.U_ID).ExecuteCommand();
        MsgShow("用户编号:" + SelectUser.U_ID + "\n删除成功!");
        UserList = new ShowDataViewModel().GetUsers();

    }
    public void SelectionUser(object parameter)
    {
        DataGrid grid = (DataGrid)parameter;
        //使数据的复制变为深复制,需要实现ICloneable接口
        if (grid.SelectedItem!=null)
        {
            SelectUser = (Users)((Users)grid.SelectedItem).Clone();
        }           
    }
    #endregion
}

7、View新建窗体

点击查看代码
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*"/>
            <RowDefinition Height="3*"/>
            <RowDefinition Height="1.5*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="dgUser" IsReadOnly="True" AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Left" ItemsSource="{Binding UserList}" Width="444">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged" >
                    <i:InvokeCommandAction Command="{Binding SelectionCommand}" CommandParameter="{Binding ElementName=dgUser}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding U_ID}" Header="编号"/>
                <DataGridTextColumn Binding="{Binding U_Name}" Header="姓名" Width="100"/>
                <DataGridTextColumn Binding="{Binding U_Age}" Header="年龄"/>
                <DataGridTextColumn Binding="{Binding U_Sex}" Header="性别" Width="60"/>
                <DataGridTextColumn Binding="{Binding U_Tel}" Header="电话" Width="172"/>
            </DataGrid.Columns>
        </DataGrid>
        <GroupBox Header="用户基本信息" Grid.Row="1">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Column="0" Grid.Row="0" Orientation="Horizontal">
                    <Label x:Name="lblID" Content="编号:" VerticalAlignment="Center" />
                    <TextBox x:Name="tbxID" IsEnabled ="False"  Text="{Binding SelectUser.U_ID}" VerticalAlignment="Center" MaxLength="5" Height="22"  Width="90"/>
                </StackPanel>
                <StackPanel Grid.Column="1" Grid.Row="0" Orientation="Horizontal">
                    <Label x:Name="lblName"  Content="姓名:" VerticalAlignment="Center" />
                    <TextBox x:Name="tbxName" Text="{Binding SelectUser.U_Name}" VerticalAlignment="Center" Height="22" MaxLength="6" Width="90"/>
                </StackPanel>
                <StackPanel Grid.Column="2" Grid.Row="0" Orientation="Horizontal">
                    <Label x:Name="lblAge" Content="年龄:" VerticalAlignment="Center" />
                    <TextBox x:Name="tbxAge" Text="{Binding SelectUser.U_Age}" VerticalAlignment="Center" Height="22" MaxLength="4" Width="90"/>
                </StackPanel>
                <StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
                    <Label x:Name="lblSex" Content="性别:" VerticalAlignment="Center"/>
                    <ComboBox Text="{Binding SelectUser.U_Sex}"  SelectedIndex="0" x:Name="cbxSex" VerticalAlignment="Center"  Width="90">
                        <ComboBoxItem Tag="1" Content="男"/>
                        <ComboBoxItem Tag="2" Content="女"/>
                    </ComboBox>
                </StackPanel>
                <StackPanel  Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2" Orientation="Horizontal">
                    <Label x:Name="lblRemarks" Content="电话:" VerticalAlignment="Center"/>
                    <TextBox x:Name="tbxRemarks" Text="{Binding SelectUser.U_Tel}" VerticalAlignment="Center" Height="22" Width="235" />
                </StackPanel>
            </Grid>
        </GroupBox>
        <GroupBox Header="功能操作" Grid.Row="2">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <Button x:Name="btnSave" Command="{Binding AddCommand}" Content="新增" VerticalAlignment="Center"  Width="69" Height="19" Margin="10,0,10,0" />
                <Button x:Name="btnUpdate" Command="{Binding UpdateCommand}" Content="修改" VerticalAlignment="Center" Width="69" Height="19" Margin="10,0,10,0"/>
                <Button x:Name="btnDelete" Command="{Binding DeleteCommand}" Content="删除" VerticalAlignment="Center" Width="69" Height="19" Margin="10,0,10,0"/>
            </StackPanel>
        </GroupBox>
    </Grid>

ps:下载地址:链接:链接:https://pan.baidu.com/s/1GECuLU3OwwtnPQDv-TvuhA?pwd=pqio

posted @ 2023-12-23 15:34  六子12138  阅读(751)  评论(6编辑  收藏  举报