使用wpf mvvm light sqlsugar 搭建增删改框架

   本项目提取了增删改查的基础方法,后续可以通过创建页面,继承vm来实现数据操作。可以通过扩展子类,来实现多表格关联查询操作。

目录

1、创建数据库实体类

2、创建viewmodel

3、创建子页面

子页面代码

4、创建主页面

5、其它辅助类


1、创建数据库实体类

    using PropertyChanged; 

    [AddINotifyPropertyChangedInterface]
    public class HisBaseInfo
    {
        public virtual decimal PrimaryKey { get; set; } 
    }

     ///


    /// 
    ///

    [SugarTable("his_Hospital")]
    public class HisHospital:HisBaseInfo
    {
        ///
        ///  
        ///

         [SugarColumn(ColumnName="ID" ,IsPrimaryKey = true ,IsIdentity = true  )]
        public override decimal PrimaryKey { get; set; }
        ///
        ///  
        ///

        [SugarColumn(ColumnName="HospitalID"    )]
         public string HospitalID { get; set; }
        ///
        ///  
        ///

         [SugarColumn(ColumnName="HospitalName"    )]
         public string HospitalName { get; set; }
    }

    

2、创建viewmodel

    using GalaSoft.MvvmLight;
    using InterfaceSimulator.Model;
    using InterfaceSimulator.Utility;

    public class CusViewModelBase : ViewModelBase
    {
        public EChildOperation ChildOperation { get; set; }
        public object WorkFlowParam { get; set; }

        public CusViewModelBase()
        {
           ChildOperation = UtilityHelper.GetChindWindowOperation();
           WorkFlowParam = UtilityHelper.GetWorkFlowParam();

        }
    }

    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;
    using InterfaceSimulator.Dal;
    //using InterfaceSimulator.Dal;
    using InterfaceSimulator.Pages.BaseInfo;
    using InterfaceSimulator.Utility;
    using System;
    using System.Collections.Generic;
    // using PropertyChanged;
    //using PropertyChanged;
    using System.Linq;
    using System.Windows;
    using System.Windows.Navigation;

    public class ViewModelBaseInfo : CusViewModelBase where T : Dal.HisBaseInfo, new()
    { 

        public ViewModelBaseInfo():base()
        { 

            if (this.IsInDesignMode)
            { 
            }
             

            if (ChildOperation == Model.EChildOperation.Modify || ChildOperation == Model.EChildOperation.Delete)
            {

                if (base.WorkFlowParam != null)
                {
                    QueryData(primarykey: ((T)WorkFlowParam).PrimaryKey.ToString());
                }
            }

        }


        public Dal.DataBaseHelper dal = new Dal.DataBaseHelper();

        

        #region DataInfo


        private T _data = new T() {  };
        public T Data
        {
            get => _data;
            set {
                _data = value;                
                RaisePropertyChanged(()=> Data); 
            }
        }

        private List _dtaList = null;
        public List DataList {
            get =>_dtaList;
            set { _dtaList = value; RaisePropertyChanged(() => DataList); }
        }

        private RelayCommand queryCommand;
        public RelayCommand QueryCommand {

            get
            {
                if (queryCommand == null)
                {
                    //查询按钮点击后 重置这个枚举 
                    UtilityHelper.SetChindWindowOperation(Model.EChildOperation.None);

                    queryCommand = new RelayCommand(()=>QueryData());
                }

                return queryCommand;
            }

            set
            {
                queryCommand = value;
            }
        }


        private RelayCommand updateCommand;
        public RelayCommand UpdateCommand
        {

            get
            {
                if (updateCommand == null)
                {
                    updateCommand = new RelayCommand(new System.Action(UpdateData)); 
                }

                return updateCommand;
            }

            set
            {
                updateCommand = value;
            }
        }

        private RelayCommand operationCommand;
        public RelayCommand OperationCommand
        {

            get
            {
                if (operationCommand == null)
                {
                    operationCommand = new RelayCommand(new System.Action(OperationData));
                }

                return operationCommand;
            }

            set
            {
                updateCommand = value;
            }


        }

        public virtual void QueryData(string primarykey= null)
        {


            if (string.IsNullOrEmpty(primarykey))
            {
               
                var _dataList = dal.Query();
                DataList = _dataList.ToList();
            }
            else
            {
              

                var dataList = dal.Query(t =>  t.PrimaryKey == Convert.ToInt32(primarykey)); 
                var _dataList = dataList.ToList();
                Data = _dataList.FirstOrDefault();

            }
        }

        public virtual void UpdateData( object param )
        {
            var childOperation = UtilityHelper.GetChindWindowOperation();

            if (childOperation == Model.EChildOperation.Add)
            {
                
                var result = dal.Add(this.Data);

                if (result > 0)
                {
                    MessageBox.Show("添加成功", "系统提示", MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show("添加失败", "系统提示", MessageBoxButton.OK);
                }
            }
            else if (childOperation == Model.EChildOperation.Modify)
            {
              
                var result = dal.Update(this.Data);

                if (result > 0)
                {
                    MessageBox.Show("保存成功", "系统提示", MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show("保存失败", "系统提示", MessageBoxButton.OK);
                }
            }
            else if (childOperation == Model.EChildOperation.Delete)
            {
                var diagResult = MessageBox.Show("是否删除", "系统提示", MessageBoxButton.OKCancel);

                if (diagResult == MessageBoxResult.OK)
                {
                     
                    var result = dal.Delete(this.Data.PrimaryKey);
                }
            }

            else if (childOperation == Model.EChildOperation.Query)
            {
                //query

                if (param != null)
                {
                    Utility.UtilityHelper.SetWorkFlowParam(param);
                }
            }
            
        }
        
        public virtual void OperationData(object param)
        {
            var childOperation = UtilityHelper.GetChindWindowOperation();

            if (param != null)
            {
                 
                Utility.UtilityHelper.SetWorkFlowParam(param);
                
            }
            
        }
         

        #endregion
    }

3、创建子页面

使用wpf mvvm light sqlsugar 搭建增删改框架_第1张图片

 

      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:InterfaceSimulator.Pages.His"
      xmlns:localVM="clr-namespace:InterfaceSimulator.ViewModel" 
      xmlns:hc="clr-namespace:HandyControl.Controls;assembly=HandyControl"
      mc:Ignorable="d" 
 
      Title="PageHisHospitalChild">

   

       

   
   
                    VerticalScrollBarVisibility="Auto"
            HorizontalScrollBarVisibility="Auto"
            >

           
               

                   
                   

               
               
                   
                   
                   
                   
                   
 
               


                                         Text="{Binding Data.PrimaryKey, Mode=TwoWay}" 
                         
                         Style="{StaticResource TextBoxExtend}"
                         hc:InfoElement.TitleWidth="100" 
                         hc:InfoElement.TitlePlacement="Top" 
                         hc:InfoElement.Title="ID" 
                         hc:InfoElement.Necessary="True" 
                         Width="200" 
                         VerticalAlignment="Center"
                         HorizontalAlignment="Left"
                         >

                                         Text="{Binding Data.HospitalID, Mode=TwoWay}"  
                         Style="{StaticResource TextBoxExtend}"
                         hc:InfoElement.TitleWidth="100" 
                         hc:InfoElement.TitlePlacement="Top" 
                         hc:InfoElement.Title="医院编号" 
                         hc:InfoElement.Necessary="True" 
                         hc:InfoElement.Placeholder="请输入医院编号"
                         Width="200" 
                         VerticalAlignment="Center"
                         HorizontalAlignment="Left"
                         >

                                         Text="{Binding Data.HospitalName, Mode=TwoWay}"
                         Style="{StaticResource TextBoxExtend}"
                         hc:InfoElement.TitleWidth="100" 
                         hc:InfoElement.TitlePlacement="Top" 
                         hc:InfoElement.Title="医院名称" 
                         hc:InfoElement.Necessary="True" 
                         hc:InfoElement.Placeholder="请输入医院名称"
                         Width="200" 
                         VerticalAlignment="Center"
                         HorizontalAlignment="Left"
                          >

               

               
               
           
       
   

子页面代码

 ///


    /// PageHospital.xaml 的交互逻辑
    ///

    public partial class PageHospitalMain : Page
    {
        public PageHospitalMain()
        {
            InitializeComponent();
        }
        private string childPageUri = "pack://application:,,,/Pages/His/PageHisHospitalChild.xaml"; 

        private void add_click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(childPageUri));

            Utility.UtilityHelper.SetChindWindowOperation(EChildOperation.Add);
        }

        private void update_click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(childPageUri));

            Utility.UtilityHelper.SetChindWindowOperation(EChildOperation.Modify);
        }

        private void drop_click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(childPageUri));

            Utility.UtilityHelper.SetChindWindowOperation(EChildOperation.Delete);
        }
    }

4、创建主页面

使用wpf mvvm light sqlsugar 搭建增删改框架_第2张图片

 

      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:InterfaceSimulator.Pages.BaseInfo"
      mc:Ignorable="d" 
      xmlns:localVM="clr-namespace:InterfaceSimulator.ViewModel" 
      d:DesignHeight="450" d:DesignWidth="800"
      Title="PageHospital">
   

       

   
   
       
           
           
       

       
           
       

       
       

           

               
                   
                   
               

               
                   
                   
                   
               

                     


               

               

               
           
       

                       ItemsSource="{Binding Path = DataList}" 
                   
                   AutoGenerateColumns="True"
                   HeadersVisibility="All" RowHeaderWidth="60" 
                   SelectionMode="Single"
                   SelectionUnit="FullRow"
                   >

           
               
                   
               

           

           

               

               

           
       
   

 

5、其它辅助类

    using System;
    using System.Windows;

    public sealed class UtilityHelper
    {

        public static void SetChindWindowOperation( Model.EChildOperation childOperation)
        {
            Application.Current.Properties["child_operation"] = childOperation;
        }

        public static Model.EChildOperation  GetChindWindowOperation()
        {
            Model.EChildOperation operation = Model.EChildOperation.None;
            //Application.Current.Properties["child_operation"]  ;

            if (Application.Current.Properties["child_operation"] != null)
            {

                operation = ( (Model.EChildOperation) Enum.Parse(typeof(Model.EChildOperation), Application.Current.Properties["child_operation"].ToString()));
                //int tempOp = 0;

                //int.TryParse(Application.Current.Properties["child_operation"].ToString(), out tempOp);

                //operation = (Model.EChildOperation)tempOp;
            }

           return operation;
        }


        public static void SetWorkFlowParam(object obj)
        {
            Application.Current.Properties["work_flow_param"] = obj;
        }


        public static object GetWorkFlowParam()
        {
            object obj= Application.Current.Properties["work_flow_param"] ;

            Application.Current.Properties["work_flow_param"] = null;
            return obj;
        }

        
    }

    public enum EChildOperation
    {
        None =0,
        Add = 1,
        Modify = 2,
        Delete = 3,
        Query = 4,
        Bulkcreate = 5
    }

你可能感兴趣的:(wpf)