首页 后端开发 C#.Net教程 什么是MVVM架构和数据绑定?

什么是MVVM架构和数据绑定?

Jun 24, 2017 am 09:25 AM
mvvm 数据 理解 绑定

 

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

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

 

绑定后:

2、架构介绍:

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

   xaml中:

       

               

      

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

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

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

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

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

3、TextBox绑定:

  

4、Button绑定:

   

5、CheckBox绑定:

  

   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}" />
登录后复制

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

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

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 List<CusGroup> csGroupsAll;public List<CusGroup> CsGroupsAll
        {get { return csGroupsAll; }set{
                csGroupsAll = value; //设定值OnPropertyChanged("CsGroupsAll"); //在属性更改后,通知            }
        }private List<CusGroup> csGroupsMinPrestore;public List<CusGroup> CsGroupsAllMinPrestore
        {get { return csGroupsMinPrestore; }set{
                csGroupsMinPrestore = value; //设定值OnPropertyChanged("CsGroupsAllMinPrestore"); //在属性更改后,通知            }
        }//CusGroup对象private CusGroup csGroup;public CusGroup CsGroup
        {get { return csGroup; }set{ csGroup = value;
                OnPropertyChanged("CsGroup"); }
        }/// <summary>/// /// </summary>private string strCMBselectValue;public string StrCMBselectValue
        {get { return strCMBselectValue; }set{if (value != null)
                {
                    strCMBselectValue = value;
                    OnPropertyChanged("StrCMBselectValue");
                }
            }
        }/// <summary>/// ComboBoxDataModel:作为一个ComboBox的对象,可以理解为数据源/// </summary>private ObservableCollection<ComboBoxDataModel> lstCSGDownLevelID;public ObservableCollection<ComboBoxDataModel> 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 DelegateCommand<string> BtnChangedCommand { get; set; }public DelegateCommand<CusGroup> TxtChangedCommand { get; set; }        #endregionpublic CusGroupEditViewModel()
        {
            CGS = new CusGroupService();
            CsGroupsAll = new List<CusGroup>();
            csGroup = new CusGroup();
            LstCSGDownLevelID = new ObservableCollection<ComboBoxDataModel>();
            BtnChangedCommand = new DelegateCommand<string>(MenuClick);
            TxtChangedCommand = new DelegateCommand<CusGroup>(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/// <summary>/// 获取全部Group/// </summary>private 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();//设置降档分组默认值        }/// <summary>/// 添加/// </summary>/// <param name="cg"></param>private 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;
            }
        }/// <summary>/// 修改/// </summary>/// <param name="cg"></param>private 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();
            }
        }/// <summary>///删除方法(实为更新)/// </summary>/// <param name="cg"></param>private 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;
            }
        }/// <summary>/// 插入和更新方法调用/// </summary>private void Save()
        {if (ErrorCount > 0)
            {//判断必填数据是否为空:为空则提示MessageBox.Show("请核对所填数据", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);return;
            }if (bIsAdd)
                AddCusGroup(CsGroup);elseUpdateCusGroup(CsGroup);
        }/// <summary>/// 获取降档分组下拉列表的值,并指定默认值/// </summary>/// <param name="value"></param>private 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);
            }
        }/// <summary>/// 排除当前列的降档ID和对应的Name/// </summary>private 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 });
            }
        }/// <summary>/// 获取列表中所有降档ID和对应的Name/// </summary>private 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();
            List<CusGroup> lstTextChange = new List<CusGroup>();
            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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

使用ddrescue在Linux上恢复数据 使用ddrescue在Linux上恢复数据 Mar 20, 2024 pm 01:37 PM

DDREASE是一种用于从文件或块设备(如硬盘、SSD、RAM磁盘、CD、DVD和USB存储设备)恢复数据的工具。它将数据从一个块设备复制到另一个块设备,留下损坏的数据块,只移动好的数据块。ddreasue是一种强大的恢复工具,完全自动化,因为它在恢复操作期间不需要任何干扰。此外,由于有了ddasue地图文件,它可以随时停止和恢复。DDREASE的其他主要功能如下:它不会覆盖恢复的数据,但会在迭代恢复的情况下填补空白。但是,如果指示工具显式执行此操作,则可以将其截断。将数据从多个文件或块恢复到单

开源!超越ZoeDepth! DepthFM:快速且精确的单目深度估计! 开源!超越ZoeDepth! DepthFM:快速且精确的单目深度估计! Apr 03, 2024 pm 12:04 PM

0.这篇文章干了啥?提出了DepthFM:一个多功能且快速的最先进的生成式单目深度估计模型。除了传统的深度估计任务外,DepthFM还展示了在深度修复等下游任务中的最先进能力。DepthFM效率高,可以在少数推理步骤内合成深度图。下面一起来阅读一下这项工作~1.论文信息标题:DepthFM:FastMonocularDepthEstimationwithFlowMatching作者:MingGui,JohannesS.Fischer,UlrichPrestel,PingchuanMa,Dmytr

谷歌狂喜:JAX性能超越Pytorch、TensorFlow!或成GPU推理训练最快选择 谷歌狂喜:JAX性能超越Pytorch、TensorFlow!或成GPU推理训练最快选择 Apr 01, 2024 pm 07:46 PM

谷歌力推的JAX在最近的基准测试中性能已经超过Pytorch和TensorFlow,7项指标排名第一。而且测试并不是在JAX性能表现最好的TPU上完成的。虽然现在在开发者中,Pytorch依然比Tensorflow更受欢迎。但未来,也许有更多的大模型会基于JAX平台进行训练和运行。模型最近,Keras团队为三个后端(TensorFlow、JAX、PyTorch)与原生PyTorch实现以及搭配TensorFlow的Keras2进行了基准测试。首先,他们为生成式和非生成式人工智能任务选择了一组主流

iPhone上的蜂窝数据互联网速度慢:修复 iPhone上的蜂窝数据互联网速度慢:修复 May 03, 2024 pm 09:01 PM

在iPhone上面临滞后,缓慢的移动数据连接?通常,手机上蜂窝互联网的强度取决于几个因素,例如区域、蜂窝网络类型、漫游类型等。您可以采取一些措施来获得更快、更可靠的蜂窝互联网连接。修复1–强制重启iPhone有时,强制重启设备只会重置许多内容,包括蜂窝网络连接。步骤1–只需按一次音量调高键并松开即可。接下来,按降低音量键并再次释放它。步骤2–该过程的下一部分是按住右侧的按钮。让iPhone完成重启。启用蜂窝数据并检查网络速度。再次检查修复2–更改数据模式虽然5G提供了更好的网络速度,但在信号较弱

BTCC教学:如何在BTCC交易所绑定使用MetaMask钱包? BTCC教学:如何在BTCC交易所绑定使用MetaMask钱包? Apr 26, 2024 am 09:40 AM

MetaMask(中文也叫小狐狸钱包)是一款免费的、广受好评的加密钱包软件。目前,BTCC已支持绑定MetaMask钱包,绑定后可使用MetaMask钱包进行快速登入,储值、买币等,且首次绑定还可获得20USDT体验金。在BTCCMetaMask钱包教学中,我们将详细介绍如何注册和使用MetaMask,以及如何在BTCC绑定并使用小狐狸钱包。MetaMask钱包是什么?MetaMask小狐狸钱包拥有超过3,000万用户,是当今最受欢迎的加密货币钱包之一。它可免费​​使用,可作为扩充功能安装在网络

超级智能体生命力觉醒!可自我更新的AI来了,妈妈再也不用担心数据瓶颈难题 超级智能体生命力觉醒!可自我更新的AI来了,妈妈再也不用担心数据瓶颈难题 Apr 29, 2024 pm 06:55 PM

哭死啊,全球狂炼大模型,一互联网的数据不够用,根本不够用。训练模型搞得跟《饥饿游戏》似的,全球AI研究者,都在苦恼怎么才能喂饱这群数据大胃王。尤其在多模态任务中,这一问题尤为突出。一筹莫展之际,来自人大系的初创团队,用自家的新模型,率先在国内把“模型生成数据自己喂自己”变成了现实。而且还是理解侧和生成侧双管齐下,两侧都能生成高质量、多模态的新数据,对模型本身进行数据反哺。模型是啥?中关村论坛上刚刚露面的多模态大模型Awaker1.0。团队是谁?智子引擎。由人大高瓴人工智能学院博士生高一钊创立,高

特斯拉机器人进厂打工,马斯克:手的自由度今年将达到22个! 特斯拉机器人进厂打工,马斯克:手的自由度今年将达到22个! May 06, 2024 pm 04:13 PM

特斯拉机器人Optimus最新视频出炉,已经可以在厂子里打工了。正常速度下,它分拣电池(特斯拉的4680电池)是这样的:官方还放出了20倍速下的样子——在小小的“工位”上,拣啊拣啊拣:这次放出的视频亮点之一在于Optimus在厂子里完成这项工作,是完全自主的,全程没有人为的干预。并且在Optimus的视角之下,它还可以把放歪了的电池重新捡起来放置,主打一个自动纠错:对于Optimus的手,英伟达科学家JimFan给出了高度的评价:Optimus的手是全球五指机器人里最灵巧的之一。它的手不仅有触觉

首个自主完成人类任务机器人出现,五指灵活速度超人,大模型加持虚拟空间训练 首个自主完成人类任务机器人出现,五指灵活速度超人,大模型加持虚拟空间训练 Mar 11, 2024 pm 12:10 PM

这周,由OpenAI、微软、贝佐斯和英伟达投资的机器人公司FigureAI宣布获得接近7亿美元的融资,计划在未来一年内研发出可独立行走的人形机器人。而特斯拉的擎天柱也屡屡传出好消息。没人怀疑,今年会是人形机器人爆发的一年。一家位于加拿大的机器人公司SanctuaryAI最近发布了一款全新的人形机器人Phoenix。官方号称它能以和人类一样的速率自主完成很多工作。世界上第一台能以人类速度自主完成任务的机器人Pheonix可以轻轻地抓取、移动并优雅地将每个对象放置在它的左右两侧。它能够自主识别物体的

See all articles