WPF +MVVM模式下的增删改查

1、项目结构图,如下图:

下面的windowsAero和WpfBase可以忽略掉。里面只是加了一个特效。

2、实体Model(Entity),如下图:

3、BLL和Dal我就不重复了。无非就是增删改查,对数据库的操作。

4、View视图,如下图:

这样整个项目就比较清晰了。

5、事件类,也就是绑定在view里面需要的事件

 public class RelayCommand : ICommand
    {

        private bool _isenabled;
        private Action _handler = null;
        public RelayCommand(Action handler)
        {
            _handler = handler;
        }

        /// <summary>
        ///
        /// </summary>
        public bool IsEnabled
        {
            get { return _isenabled; }
            set
            {
                _isenabled = value;
                if (CanExecuteChanged != null)
                {
                    this.CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// 是否启用
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            //throw new NotImplementedException();
            return IsEnabled;
        }

        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            //throw new NotImplementedException();
            _handler();
        }
    }

定义好此类之后则可以开始做增删改查操作。

六、ViewModel

   一、首先是baseViewModel

      public class BaseViewModel
    {
        /// <summary>
        /// 服务
        /// </summary>
        protected static ServiceReference1.Service1Client _service = null;
        /// <summary>
        /// 用户姓名
        /// </summary>
        protected static string UserName = null;
        /// <summary>
        /// 用户ID
        /// </summary>
        protected static int UserID = 0;
        /// <summary>
        /// 级别ID
        /// </summary>
        protected static int LevelID = 0;
        /// <summary>
        /// 操作的窗体
        /// </summary>
        protected Window windows = null;
        /// <summary>
        ///
        /// </summary>
        public BaseViewModel()
        {
            if (_service == null)
            {
                _service = new ServiceReference1.Service1Client();//这个是我调用wcf的方法。
            }
        }

二、CompanyViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Model;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows;

 

 

  public class CompanyInfoViewModel : BaseViewModel, INotifyPropertyChanged
    {
        private ObservableCollection<CompanyInfoModel> _companyInfoList;
        public ObservableCollection<CompanyInfoModel> CompanyInfoList
        {
            get
            {
                return _companyInfoList;
            }
            set
            {
                if (_companyInfoList != value)
                {
                    _companyInfoList = value;
                    OnPropertyChanged("CompanyInfoList");
                }
            }
        }

        public CompanyInfoViewModel()
        {
            //构造函数中初始化家庭成员列表
            CompanyInfoModel model = new CompanyInfoModel();
            List<CompanyInfoModel> list = _service.GetCompanyInfoByPage(0, model).ToList();
            _companyInfoList = new ObservableCollection<CompanyInfoModel>(list);

            _addCompanyCommand = new RelayCommand(addCompanyCommand) { IsEnabled = true };
            _searchCompanyCommand = new RelayCommand(searchCompanyCommand) { IsEnabled = true };
            _delCompanyCommand = new RelayCommand(delCompanyCommand) { IsEnabled = true };
            _updCompanyCommand = new RelayCommand(updCompanyCommand) { IsEnabled = true };
        }

        #region 绑定的事件

        private ICommand _addCompanyCommand;
        public ICommand AddCompanyCommand
        {
            get { return _addCompanyCommand; }
        }

        private ICommand _searchCompanyCommand;
        public ICommand SearchCompanyCommand
        {
            get { return _searchCompanyCommand; }
        }

        private ICommand _delCompanyCommand;
        public ICommand DelCompanyCommand
        {
            get { return _delCompanyCommand; }
        }

        private ICommand _updCompanyCommand;
        public ICommand UpdCompanyCommand
        {
            get { return _updCompanyCommand; }
        }

        private CompanyInfoModel _companyModel = null;
        public CompanyInfoModel CompanyModel
        {
            get
            {
                return _companyModel;
            }
            set
            {
                if (_companyModel != value)
                {
                    _companyModel = value;
                    OnPropertyChanged("CompanyModel");
                }
            }
        }
        #endregion

        #region 条件
        private string _companyName = "";
        public string CompanyName
        {
            get
            {
                return _companyName;
            }
            set
            {
                if (_companyName != value)
                {
                    _companyName = value;
                    OnPropertyChanged("CompanyName");
                }
            }
        }

        private string _companyNo = "";
        public string CompanyNo
        {
            get
            {
                return _companyNo;
            }
            set
            {
                if (_companyNo != value)
                {
                    _companyName = value;
                    OnPropertyChanged("CompanyNo");
                }
            }
        }
        #endregion

        #region 增删改查
       
        /// <summary>
        /// 查询
        /// </summary>
        public void searchCompanyCommand()
        {
            ObservableCollection<CompanyInfoModel> list = null;
            CompanyInfoModel model = new CompanyInfoModel();
            if (!string.IsNullOrEmpty(CompanyName))
            {
                model.CompanyName = CompanyName;
            }
            if (!string.IsNullOrEmpty(CompanyNo))
            {
                model.CompanyNo = CompanyNo;
            }
            var companyList = _service.GetCompanyInfoByPage(0, model);
            if (companyList != null)
            {
                list = new ObservableCollection<CompanyInfoModel>(companyList.ToList());
                CompanyInfoList = list;
            }
            else
            {
                CompanyInfoList.Clear();
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        public void delCompanyCommand()
        {
            if (CompanyModel != null)
            {
                CompanyInfoList.Remove(CompanyModel);
                MessageBox.Show("删除单位信息成功!");
            }
            else
            {
                MessageBox.Show("删除单位信息失败,请重试");
            }
        }


        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="model"></param>
        public void updEvenData(CompanyInfoModel model)
        {
            if (model != null)
            {
                if (windows != null)
                {
                    windows.Close();
                    windows = null;
                }
                MessageBox.Show("更新成功");
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        public void updCompanyCommand()
        {
            SetCompanyInfoViewModel setCompanyView = new SetCompanyInfoViewModel();
            AddCompanyInfo add = new AddCompanyInfo();
            setCompanyView.addDataEvent += new addDataDelegate(updEvenData);
            setCompanyView.Model = CompanyModel;
            windows = add;
            add.DataContext = setCompanyView;
            add.ShowDialog();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        public void addevenData(CompanyInfoModel model)
        {
            if (model != null)
            {
                //    List<CompanyInfoModel> list = new List<CompanyInfoModel>();
                //  list.Add(model);
                // if (_service.AddCompanyInfoBeginTransaction(list.ToArray()))
                // {
                CompanyInfoList.Add(model);
                if (windows != null)
                {
                    windows.Close();
                    windows = null;
                }
                MessageBox.Show("添加成功");
                //}
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        public void addCompanyCommand()
        {
            SetCompanyInfoViewModel setCompanyView = new SetCompanyInfoViewModel();
            AddCompanyInfo add = new AddCompanyInfo();
            setCompanyView.addDataEvent += new addDataDelegate(addevenData);
            setCompanyView.Model = new CompanyInfoModel();
            windows = add;
            add.DataContext = setCompanyView;
            add.ShowDialog();
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }

 

在这里我要说明一下,在类里面我都去掉了命名空间, 这个东西需要你自己加上去。而不是直接复制下来拿来用就可以了

 

CompanyViewModel已经实现了,那么就是View了。

三、View如下图

绑定如下:

<src:WinFormsBase x:Class="OptWpfApp.CompanyInfo"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WpfBase;assembly=WpfBase"
         Title="单位信息" 
          Height="500"  Width="1000" ResizeMode="NoResize"  WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Label Content="单位名称:" Margin="28,56,881,20" Name="label1" />
        <TextBox Height="23"  Margin="103,57,715,20"  Text="{Binding CompanyName}" />
        <Label Content="单位简码:" Margin="30,15,879,60" Name="label2"  Width="69" Height="25" />
        <TextBox Height="23" Margin="103,16,715,61" Name="txtCompanyNo" Width="160" />
        <Label Content="审核状态:"   Margin="283,17,619,58" Name="label3" />
        <RadioButton Content="全部" Height="16" Margin="357,23,576,61" Name="rbtnAll" />
        <RadioButton Content="审核通过" Height="16"   Margin="410,23,498,61" Name="rbtnOk" />
        <RadioButton Content="审核未通过" Height="16"  Margin="485,24,414,60" Name="rbtnNo" />
        <CheckBox Height="16"  Margin="570,24,336,60" Name="cbRecord" Content="历史记录" />
        <Button Content="查询"  Margin="798,20,104,56" Command="{Binding SearchCompanyCommand}"  />
        <Button Content="新增"  Margin="890,20,12,56" Command="{Binding AddCompanyCommand}"  />
        <DataGrid  AutoGenerateColumns="False"  Grid.Row="1"  Margin="1,0,0,25"
                   Name="dataGrid1"
                   ItemsSource="{Binding CompanyInfoList}"
                   CanUserDeleteRows="False" SelectedItem="{Binding CompanyModel,Mode=TwoWay}"
                   CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding ID}" Header="ID"  Visibility="Hidden" />
                <DataGridTextColumn Binding="{Binding CompanyNo}" Header="单位简码" Width="150"/>
                <DataGridTextColumn Binding="{Binding CompanyName}" Header="名称" Width="150"/>
                <DataGridTextColumn Binding="{Binding RegisteredAddress}" Header="注册地址" Width="150"/>
                <DataGridTextColumn Binding="{Binding OfficeAddress}" Header="办公地址" Width="150"/>
                <DataGridTemplateColumn x:Name="dataGrid1Sel" Header="选择"   Width="80">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="btndelete" Content="选择"  />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn x:Name="dataGrid1Upd" Header="修改"  Width="80">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="btnUpdate" Content="修改"
                                       Command="{Binding Path=DataContext.UpdCompanyCommand,
                                RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                                    />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn x:Name="dataGrid1Del" Header="删除"   Width="80">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="btnDelete" Content="删除"
                                    Command="{Binding Path=DataContext.DelCompanyCommand,
                                RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>

                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</src:WinFormsBase>
红色是因为我继承了这个类,如果你们没有继承,改成windows即可。

cs如下图:

这样列表页就已经完成。 在这里在啰嗦一下:WinFormsBase改成Window 即可。

在是增加和编辑 ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Model;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows;


namespace OptWpfApp
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="model"></param>
    public delegate void addDataDelegate(CompanyInfoModel model);

    public class SetCompanyInfoViewModel : BaseViewModel, INotifyPropertyChanged
    {

        /// <summary>
        ///
        /// </summary>
        public event addDataDelegate addDataEvent;

        public SetCompanyInfoViewModel()
        {
            _saveCompanyCommand = new RelayCommand(saveCompany) { IsEnabled = true };
        }

        /// <summary>
        /// 保存
        /// </summary>
        public void saveCompany()
        {
            CompanyInfoModel model = new CompanyInfoModel()
            {
                CompanyNo = Model.CompanyNo,
                CompanyName = Model.CompanyName,
                RegisteredAddress = RegisteredAddress,
                OfficeAddress = OfficeAddress,
                CorporateRepresentative = CorporateRepresentative,
                RegisteredCapital = RegisteredCapital,
                ScopeBusiness = ScopeBusiness,
                Code = Code,
                CompanyCreateTime = CompanyCreateTime,
                YingYeStartTime = YingYeStartTime,
                YingYeEndTime = YingYeEndTime
            };
            if (addDataEvent != null)
            {
                addDataEvent(model);
            }
        }

        #region 绑定的事件
        private ICommand _saveCompanyCommand;
        public ICommand saveCompanyCommand
        {
            get { return _saveCompanyCommand; }
        }
        #endregion

        #region 绑定的实体


        /// <summary>
        /// 公司简称代码,例如0000
        /// </summary>
        private string _companyNo = "";
        public string CompanyNo
        {
            get
            {
                return _companyNo;
            }
            set
            {
                if (_companyNo != value)
                {
                    _companyNo = value;
                    OnPropertyChanged("CompanyNo");
                }
            }
        }

        /// <summary>
        /// 单位名称
        /// </summary>
        private string _companyName = "";
        public string CompanyName
        {
            get
            {
                return _companyName;
            }
            set
            {
                if (_companyName != value)
                {
                    _companyName = value;
                    OnPropertyChanged("CompanyName");
                }
            }
        }

        /// <summary>
        /// 公司注册地址
        /// </summary>
        private string _registeredAddress = "";
        public string RegisteredAddress
        {
            get
            {
                return _registeredAddress;
            }
            set
            {
                if (_registeredAddress != value)
                {
                    _registeredAddress = value;
                    OnPropertyChanged("RegisteredAddress");
                }
            }
        }

        /// <summary>
        /// 办公地址
        /// </summary>
        private string _officeAddress = "";
        public string OfficeAddress
        {
            get
            {
                return _officeAddress;
            }
            set
            {
                if (_officeAddress != value)
                {
                    _officeAddress = value;
                    OnPropertyChanged("OfficeAddress");
                }
            }
        }

        /// <summary>
        /// 法人代表
        /// </summary>
        private string _corporateRepresentative = "";
        public string CorporateRepresentative
        {
            get
            {
                return _corporateRepresentative;
            }
            set
            {
                if (_corporateRepresentative != value)
                {
                    _corporateRepresentative = value;
                    OnPropertyChanged("_corporateRepresentative");
                }
            }
        }


        /// <summary>
        /// 注册资金
        /// </summary>
        private decimal _registeredCapital = 0;
        public decimal RegisteredCapital
        {
            get
            {
                return _registeredCapital;
            }
            set
            {
                if (_registeredCapital != value)
                {
                    _registeredCapital = value;
                    OnPropertyChanged("RegisteredCapital");
                }
            }
        }

        /// <summary>
        /// 经营范围
        /// </summary>
        private string _scopeBusiness = "";
        public string ScopeBusiness
        {
            get
            {
                return _scopeBusiness;
            }
            set
            {
                if (_scopeBusiness != value)
                {
                    _scopeBusiness = value;
                    OnPropertyChanged("ScopeBusiness");
                }
            }
        }

        /// <summary>
        /// 组织机构代码
        /// </summary>
        private string _code = "";
        public string Code
        {
            get
            {
                return _code;
            }
            set
            {
                if (_code != value)
                {
                    _code = value;
                    OnPropertyChanged("Code");
                }
            }
        }

        /// <summary>
        /// 成立日期
        /// </summary>
        private DateTime _companyCreateTime = DateTime.MaxValue;
        public DateTime CompanyCreateTime
        {
            get
            {
                return _companyCreateTime;
            }
            set
            {
                if (_companyCreateTime != value)
                {
                    _companyCreateTime = value;
                    OnPropertyChanged("CompanyCreateTime");
                }
            }
        }
        /// <summary>
        /// 营业期限开始时间
        /// </summary>
        ///
        private DateTime _yingYeStartTime = DateTime.MaxValue;
        public DateTime YingYeStartTime
        {
            get
            {
                return _yingYeStartTime;
            }
            set
            {
                if (_yingYeStartTime != value)
                {
                    _yingYeStartTime = value;
                    OnPropertyChanged("YingYeStartTime");
                }
            }
        }

        /// <summary>
        /// 营业期限结束时间
        /// </summary>
        private DateTime _yingYeEndTime = DateTime.MaxValue;
        public DateTime YingYeEndTime
        {
            get
            {
                return _yingYeEndTime;
            }
            set
            {
                if (_yingYeEndTime != value)
                {
                    _yingYeEndTime = value;
                    OnPropertyChanged("YingYeEndTime");
                }
            }
        }

        public CompanyInfoModel _model;
        public CompanyInfoModel Model
        {
            get
            {
                return _model;
            }
            set
            {
                if (_model != value)
                {
                    _model = value;
                    OnPropertyChanged("_model");
                }
            }
        }
        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}

View视图代码:

<src:WinFormsBase  x:Class="OptWpfApp.AddCompanyInfo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:src="clr-namespace:WpfBase;assembly=WpfBase"
        Title="添加单位信息" Height="500" Width="900"  ResizeMode="NoResize"  WindowStartupLocation="CenterScreen">
    <Grid  >
        <Button Content="保存" Height="23" HorizontalAlignment="Left" Margin="319,179,0,0" Name="button1" VerticalAlignment="Top" Width="75 " Command="{Binding saveCompanyCommand}" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="186,50,0,0" Name="textBox1" VerticalAlignment="Top" Width="208" Text="{Binding Model.CompanyNo}"  />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="186,102,0,0" Name="textBox2" VerticalAlignment="Top" Width="200"   Text="{Binding Model.CompanyName}"  />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="87,53,0,0" Name="textBlock2"  Text="单位编码:" VerticalAlignment="Top" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="87,106,0,0" Name="textBlock3" Text="单位名称:"  VerticalAlignment="Top" />
    </Grid>
</src:WinFormsBase>

 

另外里面引用的实体就是我上面定义的实体。

此次MVVM增删改查已经完成。

 

 

后台cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfBase;
using Model;

namespace OptWpfApp
{
    /// <summary>
    /// AddCompanyInfo.xaml 的交互逻辑
    /// </summary>
    public partial class AddCompanyInfo : WinFormsBase
    {
        public AddCompanyInfo()
        {
            InitializeComponent();
        }
    }
}

 

则是什么都没有。绑定的值全部都在ViewModel里面。


 

  • 6
    点赞
  • 19
    评论
  • 6
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏

xugan666

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者