這篇文章主要講解了“MVVM架構和數據綁定是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“MVVM架構和數據綁定是什么”吧!
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\16\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\16\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架構和數據綁定是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。