>  기사  >  백엔드 개발  >  MVVM 아키텍처와 데이터 바인딩이란 무엇입니까?

MVVM 아키텍처와 데이터 바인딩이란 무엇입니까?

零下一度
零下一度원래의
2017-06-24 09:25:163044검색

 

(申明:最近在做一个练习,写点东西,谨供参考。)

1、界面展示:其中的布局和样式就不说了,重点在MVVM架构和数据绑定(Model层使用EF(Entity Framework)实体框架,不做介绍)。

 

绑定后:

2、架构介绍:

在Views层中新建CusGroupEditWindow窗体,ViewModels中建立CusGroupEditViewModel类,在窗体的xaml或者cs中引用ViewModels对应类:

   xaml中:

    c879f5c3c9893e45ba2ce7d26e997114   

          92c72cd9b9c57deded9b4898c5a2dbe2 1da84c50fa7328704b2ce9dda53aedda     

      7473f81b006ddc8e53f2d378bc7dce62

  cs:DataContext = CusGroupEditViewModel。(添加引用路径)

/***********************************************/

*CsGroup是在ViewModel中定义的一个CusGroup对象,    *

*CusGroup对象是在SQL数据库中的表,在EF中的对象。    *

/***********************************************/

3、TextBox绑定:

  ff1681ddee25e4aeb6879b3c67fb00b5

4、Button绑定:

  5d362da14155c388b940c2445466edf6         

            29deedf2cd939b8bccbf37085c6a617a8b6de9c7d98b148f30b5dd6899a18be9

      a1cb88e6789f399807801ea3799938af 

dfca9557cc388af630eeba6df35e96f8

c05eec64ed02ad0975536668a09b61b7

5、CheckBox绑定:

  04efaf97de328fe03fc57ff1cb705f93

  456c2222d60e5b20af2a55c567b254f7 6、ComboBox绑定:

6、ComboBox绑定:

<ComboBox MaxWidth="150" Width="100" SelectedValue="{Binding StrCMBselectValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Text"
                                              SelectedValuePath="Value" ItemsSource="{Binding LstCSGDownLevelID, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />

 

 

 b33558531c9bd20894e37c6740957f48

65f8f648affa7f9bf7c2b3b9504200a2                                                 

7、DataGrid绑定:

<DataGrid ColumnWidth="*" SelectedItem="{Binding CurrentSelectItem}"  ItemsSource="{Binding CsGroupsAll}" AutoGenerateColumns="False"  IsReadOnly="True" >
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="分组编号" Binding="{Binding Code}" />
                                    <DataGridTextColumn Header="分组名称" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>

 

/***************************************************************/

        //DataGrid当前选择对象private CusGroup currentSelectItem;public CusGroup CurrentSelectItem
        {get { return currentSelectItem; }set{
                currentSelectItem = value;

                GetCutCmbSelect(value);
            }
        }
View Code

 

3a102498773156c85fe31b421356ccfb

/***************************************************************/

 

ViewModel 中的代码:

   
   
using HeYin.ERP.DataModels;using HeYin.ERP.IServices;using HeYin.ERP.Models;using HeYin.ERP.Services;using Microsoft.Practices.Prism.Commands;using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Windows;using System.Text.RegularExpressions;using System.Windows.Controls;namespace HeYin.ERP.Client.ViewModels.Customer
{class CusGroupEditViewModel : BaseViewModel
    {private bool bIsAdd = false;

        ICusGroupService CGS;  //调用IService接口#region Properties 属性private Guid gCsGroupID = Guid.Empty;//All CusGroupprivate List12a277596269c1ca26ae0578ebbecfb8 csGroupsAll;public List12a277596269c1ca26ae0578ebbecfb8 CsGroupsAll
        {get { return csGroupsAll; }set{
                csGroupsAll = value; //设定值OnPropertyChanged("CsGroupsAll"); //在属性更改后,通知            }
        }private List12a277596269c1ca26ae0578ebbecfb8 csGroupsMinPrestore;public List12a277596269c1ca26ae0578ebbecfb8 CsGroupsAllMinPrestore
        {get { return csGroupsMinPrestore; }set{
                csGroupsMinPrestore = value; //设定值OnPropertyChanged("CsGroupsAllMinPrestore"); //在属性更改后,通知            }
        }//CusGroup对象private CusGroup csGroup;public CusGroup CsGroup
        {get { return csGroup; }set{ csGroup = value;
                OnPropertyChanged("CsGroup"); }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// /// 039f3e95db2a684c7b74365531eb6044private string strCMBselectValue;public string StrCMBselectValue
        {get { return strCMBselectValue; }set{if (value != null)
                {
                    strCMBselectValue = value;
                    OnPropertyChanged("StrCMBselectValue");
                }
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// ComboBoxDataModel:作为一个ComboBox的对象,可以理解为数据源/// 039f3e95db2a684c7b74365531eb6044private ObservableCollection2584f245219aed0baedf79a7e59b6c50 lstCSGDownLevelID;public ObservableCollection2584f245219aed0baedf79a7e59b6c50 LstCSGDownLevelID
        {get { return lstCSGDownLevelID; }set{
                lstCSGDownLevelID = value;
                OnPropertyChanged("LstCSGDownLevelID");
            }
        }//DataGrid当前选择对象private CusGroup currentSelectItem;public CusGroup CurrentSelectItem
        {get { return currentSelectItem; }set{
                currentSelectItem = value;

                GetCutCmbSelect(value);
            }
        }private int errorCount;public int ErrorCount { get => errorCount; set => errorCount = value; }#endregion#region Commandspublic DelegateCommand98c455a79ddfebb79781bff588e7b37e BtnChangedCommand { get; set; }public DelegateCommand12a277596269c1ca26ae0578ebbecfb8 TxtChangedCommand { get; set; }        #endregionpublic CusGroupEditViewModel()
        {
            CGS = new CusGroupService();
            CsGroupsAll = new List12a277596269c1ca26ae0578ebbecfb8();
            csGroup = new CusGroup();
            LstCSGDownLevelID = new ObservableCollection2584f245219aed0baedf79a7e59b6c50();
            BtnChangedCommand = new DelegateCommand98c455a79ddfebb79781bff588e7b37e(MenuClick);
            TxtChangedCommand = new DelegateCommand12a277596269c1ca26ae0578ebbecfb8(ChangeCMBValue);

            GetAllCusGroups();
        }#region ButtonClickprivate void MenuClick(string strMessage)
        {if (string.IsNullOrEmpty(strMessage)) return;if (CsGroup == null) return;switch (strMessage)
            {case "btnCusGroupSave":
                    Save();break;case "btnCusGroupAdd":
                    Add();break;case "btnCusGroupDelete":
                    Delete();break;
            }
        }#endregion ButtonClick#region motheds/// 631fb227578dfffda61e1fa4d04b7d25/// 获取全部Group/// 039f3e95db2a684c7b74365531eb6044private void GetAllCusGroups()
        {//获取满足条件的客户分组信息            CsGroupsAll.Clear();
            CsGroupsAll = CGS.Get(s => s.IsDelete == 0);

            GetAllCMBItems();//给降档分组下拉框赋值if ((gCsGroupID == null || gCsGroupID == Guid.Empty) && CsGroupsAll.Count > 0)
                CsGroup = CsGroupsAll[0];    //给基础信息等赋值StrCMBselectValue = CsGroup.DownLevelID.ToString();//设置降档分组默认值        }/// 631fb227578dfffda61e1fa4d04b7d25/// 添加/// 039f3e95db2a684c7b74365531eb6044/// 871df4e675f01b90b299b5458b6fbd688bb7487ae6a16a43571bc14c7fcf93c2private void AddCusGroup(CusGroup cg)
        {
            cg.ID = Guid.NewGuid(); //新建分组GUIDcg.IsDelete = 0;        //默认为0:不删除cg.CreateBy = App.GetCurrentUserId();//创建人员关联员工 GUIDcg.CreateTime = DateTime.Now;  //初始化创建时间,应该使用服务器当前时间bool c = CGS.Add(cg);if (c)
            {
                MessageBox.Show(string.Format("创建新组别【{0}】成功!", CsGroup.Name), "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                GetAllCusGroups();
                bIsAdd = false;
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// 修改/// 039f3e95db2a684c7b74365531eb6044/// 871df4e675f01b90b299b5458b6fbd688bb7487ae6a16a43571bc14c7fcf93c2private void UpdateCusGroup(CusGroup cg)
        {
            bIsAdd = false;

            cg.UpdateTime = DateTime.Now;
            cg.UpdateBy = App.GetCurrentUserId();//更新人员关联员工 GUIDstring[] str = { "UpdateTime", "UpdateBy" };bool b = CGS.Edit(cg, str);if (b)
            {
                MessageBox.Show("更改组别【成功】!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                GetAllCusGroups();
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25///删除方法(实为更新)/// 039f3e95db2a684c7b74365531eb6044/// 871df4e675f01b90b299b5458b6fbd688bb7487ae6a16a43571bc14c7fcf93c2private void DeleteCusGroup(CusGroup cg)
        {
            cg.IsDelete = 1; //更改数据库删除标志cg.UpdateTime = DateTime.Now;  //更新删除时间cg.UpdateBy = App.GetCurrentUserId();//更新人员关联员工 GUIDstring[] str = { "UpdateTime", "IsDelete", "UpdateBy" };bool b = CGS.Edit(cg, str);if (b)
            {//MessageBox.Show(string.Format("已删除组别【{0}】!", CsGroup.Name), "提示", MessageBoxButton.OK, MessageBoxImage.Information);                GetAllCusGroups();
                CsGroup = new CusGroup(); //清空对象bIsAdd = true;
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// 插入和更新方法调用/// 039f3e95db2a684c7b74365531eb6044private void Save()
        {if (ErrorCount > 0)
            {//判断必填数据是否为空:为空则提示MessageBox.Show("请核对所填数据", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);return;
            }if (bIsAdd)
                AddCusGroup(CsGroup);elseUpdateCusGroup(CsGroup);
        }/// 631fb227578dfffda61e1fa4d04b7d25/// 获取降档分组下拉列表的值,并指定默认值/// 039f3e95db2a684c7b74365531eb6044/// baf7518bd06a20614696879534a64e8e8bb7487ae6a16a43571bc14c7fcf93c2private void GetCutCmbSelect(CusGroup value)
        {
            bIsAdd = false;//点击新增后,再选择列表的逻辑if (value != null)
            {
                CsGroup = CGS.GetById(value.ID);//查找出当前选中的对象gCsGroupID = CsGroup.ID;        //保存当前选择对象的GUIDif (CsGroup != null)
                {if (CsGroup.DownLevelID.HasValue)
                    {//如果降档ID有值,则默认显示,如果没有,则显示为空GetExceptCMBSelect();//刷新下拉列表,先刷新,再赋值给默认值StrCMBselectValue = CsGroup.DownLevelID.ToString();
                    }else{
                        LstCSGDownLevelID.Clear();
                        StrCMBselectValue = string.Empty;
                    }
                }
            }
        }private void Add()
        {
            bIsAdd = true;//点击新建分组时,重新获取所有降档ID对应的中文名            GetAllCMBItems();

            CsGroup = new CusGroup();
        }private void Delete()
        {if (this.CsGroup.ID == Guid.Empty || CsGroup.ID == null)
                MessageBox.Show("请选择要删除组别", "提示", MessageBoxButton.OK, MessageBoxImage.Information);else{
                MessageBoxResult msgResult = MessageBox.Show(string.Format("确定要删除分组【{0}】吗?", CsGroup.Name), "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);if (msgResult == MessageBoxResult.Yes)
                    DeleteCusGroup(CsGroup);
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// 排除当前列的降档ID和对应的Name/// 039f3e95db2a684c7b74365531eb6044private void GetExceptCMBSelect()
        {
            LstCSGDownLevelID.Clear();
            CsGroupsAllMinPrestore = CGS.Get(s => s.IsDelete == 0 && s.MinPrestore <= CsGroup.MinPrestore);foreach (var iDlID in CsGroupsAllMinPrestore)
            {if (iDlID.ID != CsGroup.ID) //去除当前选择ID对应的NameLstCSGDownLevelID.Add(new ComboBoxDataModel() { Value = iDlID.ID.ToString(), Text = iDlID.Name });
            }
        }/// 631fb227578dfffda61e1fa4d04b7d25/// 获取列表中所有降档ID和对应的Name/// 039f3e95db2a684c7b74365531eb6044private void GetAllCMBItems()
        {
            LstCSGDownLevelID.Clear();foreach (var iDlID in CsGroupsAll)
            {
                LstCSGDownLevelID.Add(new ComboBoxDataModel() { Value = iDlID.ID.ToString(), Text = iDlID.Name });
            }
        }private void ChangeCMBValue(CusGroup cgMinPrestore)
        {
            LstCSGDownLevelID.Clear();
            List12a277596269c1ca26ae0578ebbecfb8 lstTextChange = new List12a277596269c1ca26ae0578ebbecfb8();
            lstTextChange = CGS.Get(s => s.MinPrestore < cgMinPrestore.MinPrestore);foreach (var iDlID in lstTextChange)
            {
                LstCSGDownLevelID.Add(new ComboBoxDataModel() { Value = iDlID.ID.ToString(), Text = iDlID.Name });
            }
        }public void SizeChangedCommand(object obj, SizeChangedEventArgs e)
        {

            MessageBox.Show("日了狗");

        }#endregion}
}

 

View中代码:



    
        
            
        
    

    

        
            
            
        

        
            
                
                
            

            
            
                
                    
                        
                            
                                
                                

                                
                            
                        
                    

                    
                        
                            <DataGrid ColumnWidth="*" SelectedItem="{Binding CurrentSelectItem}"  ItemsSource="{Binding CsGroupsAll}" AutoGenerateColumns="False"  IsReadOnly="True" >
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="分组编号" Binding="{Binding Code}" />
                                    <DataGridTextColumn Header="分组名称" Binding="{Binding Name}" />
                                </DataGrid.Columns>
                            </DataGrid>
                        
                    
                
            

            
            
                
                    
                    
                    
                

                
                
                    
                        
                            
                        

                        
                            
                                
                                    
                                    
                                

                                
                                
                                    
                                    
                                        
                                            
                                                
                                                    
                                                    
                                                
                                            
                                        
                                    
                                

                                
                                    
                                    
                                        
                                            
                                                
                                                    
                                                    
                                                
                                            
                                        
                                    
                                
                            

                            
                                
                                    

                                    
                                        
                                            
                                                
                                                    
                                                    
                                                
                                            
                                        
                                    
                                
                            
                        
                    
                

                
                
                    
                        
                            
                                
                            

                            
                                
                                    
                                    
                                

                                
                                    
                                    
                                
                                
                                    
                                    
                                
                            
                        
                    
                

                
                
                    
                        
                            
                        

                        
                            
                                
                                    
                                    
                                

                                
                                    
                                    
                                
                                
                                    
                                    
                                
                            

                            
                                
                                    
                                    <ComboBox MaxWidth="150" Width="100" SelectedValue="{Binding StrCMBselectValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Text"
                                              SelectedValuePath="Value" ItemsSource="{Binding LstCSGDownLevelID, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
                                
                            
                        
                    
                
            
        

        
        
            
                
            
        
    

 

위 내용은 MVVM 아키텍처와 데이터 바인딩이란 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.