1、界面展示:其中的布局和样式就不说了,重点在MVVM架构和数据绑定(Model层使用EF(Entity Framework)实体框架,不做介绍)。
绑定后:
2、架构介绍:
在VIEws层中新建CusGroupEditwindow窗体,viewmodels中建立CusGroupEditviewmodel类,在窗体的xaml或者cs中引用viewmodels对应类:
xaml中:
<Window.DataContext>
<local:CusGroupEditviewmodel/> <!--(添加引用local:为CusGroupEditviewmodel的路径)-->
</Window.DataContext>
cs:DataContext = CusGroupEditviewmodel。(添加引用路径)
/***********************************************/
*CsGroup是在viewmodel中定义的一个CusGroup对象, *
*CusGroup对象是在sql数据库中的表,在EF中的对象。 *
/***********************************************/
3、TextBox绑定:
<TextBox MaxWIDth="550" WIDth="100" Text="{Binding CsGroup.Alarm,Mode=TwoWay}" />
4、button绑定:
<button WIDth="100" Height="35" margin="10" Command="{Binding BtnChangedCommand}" CommandParameter="btnCusGroupSave" Background="#fc8530" >
<TextBlock Text="保存" FontWeight="Bold" FontSize="16"></TextBlock>
</button>
<!-- Command="{Binding BtnChangedCommand}"中是在viewmodel中的委托,继承ICommoand -->
<!--CommandParameter="btnCusGroupSave" 参数-->
5、CheckBox绑定:
<CheckBox name="cbCash" margin="0,0,5,0" IsChecked="{Binding CsGroup.IsCash}"/>
<!-- IsCash 是在sql表中CusGroup中字段,bit类型--> 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}" />
<!--SelectedValue:选中CommoBox的值,Mode双向模式,属性改变时触发;displayMemberPath:显示时绑定;SelectedValuePath:表示选择下拉框某一项对应的值;ItemsSource:绑定的数据源 -->
<!-- 其中Value和Text也可理解为数据源,在viewmodel中有赋值-->
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中代码:
<clIEnt:BaseWindow x:Class="heyin.ERP.ClIEnt.VIEws.Customer.CusGroupEditwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/Expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Interaction="http://schemas.microsoft.com/Expression/2010/interactions" xmlns:Interactivity="http://schemas.microsoft.com/Expression/2010/interactivity" xmlns:CommonValIDation="clr-namespace:heyin.ERP.Common.ValIDation;assembly=heyin.ERP.Common" xmlns:clIEnt="clr-namespace:heyin.ERP.ClIEnt" mc:Ignorable="d" x:name="CusGroupWindow" Title="客户分组" Height="500" WIDth="800" windowstartupLocation="CenterOwner" Loaded="Window_Loaded" MaxBoxEnable="True" MinBoxEnable="False" > <Interactivity:Interaction.Triggers> <Interactivity:EventTrigger Eventname="SizeChanged"> <Interaction:CallMethodAction Targetobject="{Binding}" Methodname="SizeChangedCommand"/> </Interactivity:EventTrigger> </Interactivity:Interaction.Triggers> <GrID> <GrID.RowDeFinitions> <RowDeFinition Height="*" /> <RowDeFinition Height="50" /> </GrID.RowDeFinitions> <GrID GrID.Row="0"> <GrID.ColumnDeFinitions> <ColumnDeFinition WIDth="1*"/> <ColumnDeFinition WIDth="2*"/> </GrID.ColumnDeFinitions> <!-- left --> <GrID margin="5,0,5,5"> <GroupBox name="gbGroupData"> <GroupBox.headerTemplate> <DataTemplate> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock Text="客户分组" Height="20" /> <button WIDth="20" Height="20" margin="50,0,0,0" Command="{Binding DataContext.BtnChangedCommand,relativeSource={relativeSource Mode=FindAncestor,AncestorType=GroupBox}}" CommandParameter="btnCusGroupAdd" Visibility="{Binding SaveVisibility,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <Image Source="..\..\Resources\Images\Add.png" /> </button> <button WIDth="20" Height="20" margin="10,0,0,0" Command="{Binding DataContext.BtnChangedCommand,relativeSource={relativeSource Mode=FindAncestor,AncestorType=GroupBox}}" CommandParameter="btnCusGroupDelete" Visibility="{Binding SaveVisibility,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <Image Source="..\..\Resources\Images\Clear.png" /> </button> </WrapPanel> </DataTemplate> </GroupBox.headerTemplate> <GrID> <GrID GrID.Row="1"> <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> </GrID> </GrID> </GroupBox> </GrID> <!-- Right --> <GrID GrID.Column="1" margin="5"> <GrID.RowDeFinitions> <RowDeFinition Height="*"/> <RowDeFinition Height="100"/> <RowDeFinition Height="130"/> </GrID.RowDeFinitions> <!-- 基础信息 --> <GrID> <GroupBox> <GroupBox.header> <TextBlock Text="基础信息" Height="20"/> </GroupBox.header> <StackPanel> <GrID margin="0,10"> <GrID.ColumnDeFinitions> <ColumnDeFinition WIDth="*" /> <ColumnDeFinition WIDth="*" /> </GrID.ColumnDeFinitions> <TextBox Visibility="Collapsed" x:name="tbErrorCount" Text="{Binding ErrorCount, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock WIDth="60" margin="{StaticResource TextBlockmarginForMostleft}"><Run Text="分组编号" /></TextBlock> <TextBox name="txtCusGropCrod" MaxWIDth="150" WIDth="100" tooltip="{Binding relativeSource={relativeSource self},Path=(ValIDation.Errors).CurrentItem.ErrorContent}" ValIDation.Error="ValIDation_Error"> <TextBox.Text> <Binding Path="CsGroup.Code" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValIDatesOnDataErrors="True" NotifyOnValIDationError="True"> <Binding.ValIDationRules> <ExceptionValIDationRule></ExceptionValIDationRule> <CommonValIDation:requiredValIDationRule MaxLenth="15" ErrorMessage="分组编号" Isrequired="True" ValIDatesOnTargetUpdated="True" /> </Binding.ValIDationRules> </Binding> </TextBox.Text> </TextBox> </WrapPanel> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}" GrID.Column="1"> <TextBlock Text="分组名称" WIDth="60" margin="{StaticResource TextBlockmarginForMostleft}"/> <TextBox name="txtCusGropname" MaxWIDth="150" WIDth="100" tooltip="{Binding relativeSource={relativeSource self},Path=(ValIDation.Errors).CurrentItem.ErrorContent}" ValIDation.Error="ValIDation_Error"> <TextBox.Text> <Binding Path="CsGroup.name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValIDatesOnDataErrors="True" NotifyOnValIDationError="True"> <Binding.ValIDationRules> <ExceptionValIDationRule></ExceptionValIDationRule> <CommonValIDation:requiredValIDationRule MaxLenth="15" ErrorMessage="分组名称" Isrequired="True" ValIDatesOnTargetUpdated="True" /> </Binding.ValIDationRules> </Binding> </TextBox.Text> </TextBox> </WrapPanel> </GrID> <GrID> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock margin="{StaticResource TextBlockmarginForMostleft}" WIDth="60" VerticalAlignment="Center"><Run Text="分组描述" /></TextBlock> <TextBox x:name="tbRemark" textwrapPing="Wrap" AcceptsReturn="True" VerticalScrollbarVisibility="Visible" WIDth="400" Height="90" tooltip="{Binding relativeSource={relativeSource self},Path=(ValIDation.Errors).CurrentItem.ErrorContent}" ValIDation.Error="ValIDation_Error"> <TextBox.Text> <Binding Path="CsGroup.Description" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValIDatesOnDataErrors="True" NotifyOnValIDationError="True"> <Binding.ValIDationRules> <ExceptionValIDationRule></ExceptionValIDationRule> <CommonValIDation:requiredValIDationRule MaxLenth="300" ErrorMessage="分组描述" ValIDatesOnTargetUpdated="True" /> </Binding.ValIDationRules> </Binding> </TextBox.Text> </TextBox> </WrapPanel> </GrID> </StackPanel> </GroupBox> </GrID> <!-- 消费相关 --> <GrID GrID.Row="1" margin="0,10,0,10"> <GrID> <GroupBox> <GroupBox.header> <TextBlock Text="消费相关"/> </GroupBox.header> <GrID margin="0,10"> <GrID.ColumnDeFinitions> <ColumnDeFinition WIDth="*"/> <ColumnDeFinition WIDth="*"/> </GrID.ColumnDeFinitions> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock Text="消费积分" WIDth="60" Height="20" margin="{StaticResource TextBlockmarginForMostleft}" /> <TextBox name="txtCusGropJF" MaxWIDth="150" WIDth="100" Text="{Binding CsGroup.PointConversion, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> </WrapPanel> <WrapPanel GrID.Column="1" margin="{StaticResource WrapPanelmarginForInfo}" HorizontalAlignment="left" VerticalAlignment="Center"> <CheckBox name="cbCash" margin="0,0,5,0" IsChecked="{Binding CsGroup.IsCash}"/> <TextBlock Text="开通预存或储值时禁止现金交易" /> </WrapPanel> </GrID> </GroupBox> </GrID> </GrID> <!-- 预存相关 --> <GrID GrID.Row="2"> <GroupBox> <GroupBox.header> <TextBlock Text="预存相关"/> </GroupBox.header> <StackPanel> <GrID margin="0,10"> <GrID.ColumnDeFinitions> <ColumnDeFinition WIDth="*"/> <ColumnDeFinition WIDth="*"/> </GrID.ColumnDeFinitions> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock WIDth="80" margin="{StaticResource TextBlockmarginForMostleft}" ><Run Text="预存最低充值"/></TextBlock> <TextBox MaxWIDth="150" WIDth="100" Text="{Binding CsGroup.MinPrestore, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> </WrapPanel> <WrapPanel GrID.Column="1" margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock WIDth="80" Text="金额低缺报警" margin="{StaticResource TextBlockmarginForMostleft}" /> <TextBox MaxWIDth="550" WIDth="100" Text="{Binding CsGroup.Alarm,Mode=TwoWay}" /> </WrapPanel> </GrID> <GrID margin="0,5"> <WrapPanel margin="{StaticResource WrapPanelmarginForInfo}"> <TextBlock WIDth="190" Text="预存金额未达到最低要求时降档至" margin="{StaticResource TextBlockmarginForMostleft}"/> <ComboBox MaxWIDth="150" WIDth="100" SelectedValue="{Binding StrCMBselectValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" displayMemberPath="Text" SelectedValuePath="Value" ItemsSource="{Binding LstCSGDownLevelID, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> </WrapPanel> </GrID> </StackPanel> </GroupBox> </GrID> </GrID> </GrID> <!-- bottom --> <GrID GrID.Row="2"> <WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center" margin="{StaticResource WrapPanelmarginForInfo}"> <button margin="1" Command="{Binding BtnChangedCommand}" CommandParameter="btnCusGroupSave" Background="#fc8530" Style="{StaticResource SavebuttonStyle}" Visibility="{Binding SaveVisibility,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" > <TextBlock Text="保存" FontWeight="Bold" FontSize="16"></TextBlock> </button> </WrapPanel> </GrID> </GrID></clIEnt:BaseWindow>总结
以上是内存溢出为你收集整理的什么是MVVM架构和数据绑定?全部内容,希望文章能够帮你解决什么是MVVM架构和数据绑定?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)