【轉】【WPF】WPF MVVM 簡單實例


1 新建WPF 應用程序WPFMVVMExample

程序結構如下圖所示。

 

 

2 Model實現

在Model文件夾下新建業務類StudentModel(類文件StudentModel.cs),類的詳細代碼如下所示。

using System.ComponentModel;
 
namespace WPFMVVMExample.Model
{
    public class StudentModel : INotifyPropertyChanged
    {
        /// <summary>
        /// 學號
        /// </summary>
        private int studentId;
        public int StudentId
        {
            get 
            { 
                return studentId; 
            }
            set 
            { 
                studentId = value;
                NotifyPropertyChanged("StudentId");
            }
        }
 
        /// <summary>
        /// 姓名
        /// </summary>
        private string studentName;
        public string StudentName
        {
            get 
            { 
                return studentName; 
            }
            set 
            { 
                studentName = value;
                NotifyPropertyChanged("StudentName");
            }
        }
 
        /// <summary>
        /// 年齡
        /// </summary>
        private int studentAge;
        public int StudentAge
        {
            get 
            { 
                return studentAge; 
            }
            set 
            { 
                studentAge = value;
                NotifyPropertyChanged("StudentAge");
            }
        }
 
        /// <summary>
        /// Email
        /// </summary>
        private string studentEmail;
        public string StudentEmail
        {
            get 
            { 
                return studentEmail; 
            }
            set 
            { 
                studentEmail = value;
                NotifyPropertyChanged("StudentEmail");
            }
        }
 
        /// <summary>
        /// 性別
        /// </summary>
        private string studentSex;
        public string StudentSex
        {
            get 
            { 
                return studentSex; 
            }
            set 
            { 
                studentSex = value;
                NotifyPropertyChanged("StudentSex");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

StudentModel類實現了接口INotifyPropertyChanged。當類實現該接口后,便可以向執行綁定的客戶端發出某一屬性值已更改的通知。

 

3 ViewModel實現

在ViewModel文件夾下新建類文件StudentViewModel.cs,類文件的詳細代碼如下所示。

using System;
using System.Windows.Input;
using WPFMVVMExample.Model;
 
namespace WPFMVVMExample.ViewModel
{
    public class StudentViewModel
    {
        public DelegateCommand ShowCommand { get; set; }
        public StudentModel Student { get; set; }
        public StudentViewModel()
        {
            Student = new StudentModel();
            ShowCommand=new DelegateCommand();
            ShowCommand.ExecuteCommand = new Action<object>(ShowStudentData);
        }
        private void ShowStudentData(object obj)
        {
            Student.StudentId = 1;
            Student.StudentName = "tiana";
            Student.StudentAge = 20;
            Student.StudentEmail = "8644003248@qq.com";
            Student.StudentSex = "大帥哥";
        }
 
    }
 
    public class DelegateCommand : ICommand
    {
        public Action<object> ExecuteCommand = null;
        public Func<object, bool> CanExecuteCommand = null;
        public event EventHandler CanExecuteChanged;
 
        public bool CanExecute(object parameter)
        {
            if (CanExecuteCommand != null)
            {
                return this.CanExecuteCommand(parameter);
            }
            else
            {
                return true;
            }
        }
 
        public void Execute(object parameter)
        {
            if (this.ExecuteCommand != null)
            { 
                this.ExecuteCommand(parameter); 
            }
        }
 
        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}

代碼中,除了定義StudentViewModel類外,還定義了DelegateCommand類,該類實現了ICommand接口。

ICommand接口中的Execute()方法用於命令的執行,CanExecute()方法用於指示當前命令在目標元素上是否可用,當這種可用性發生改變時便會觸發接口中的CanExecuteChanged事件。

我們可以將實現了ICommand接口的命令DelegateCommand賦值給Button(命令源)的Command屬性(只有實現了ICommandSource接口的元素才擁有該屬性),這樣Button便與命令進行了綁定。

 

4 MainWindow.xaml實現

MainWindow.xaml的界面如下圖所示。

MainWindow.xaml界面的xaml代碼如下所示。

<Window x:Class="WPFMVVMExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="學號" Height="28" HorizontalAlignment="Left" Margin="54,23,0,0" Name="labelStudentId" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentId}" IsReadOnly="True" Height="23" HorizontalAlignment="Right" Margin="0,27,289,0" Name="textBoxStudentId" VerticalAlignment="Top" Width="120" />
        <Label Content="姓名" Height="28" HorizontalAlignment="Left" Margin="54,61,0,0" Name="labelStudentName" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentName}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,65,0,0" Name="textBoxStudentName" VerticalAlignment="Top" Width="120" />
        <Label Content="年齡" Height="28" HorizontalAlignment="Left" Margin="54,94,0,0" Name="labelStudentAge" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentAge}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,99,0,0" Name="textBoxStudentAge" VerticalAlignment="Top" Width="120" />
        <Label Content="Email" Height="28" HorizontalAlignment="Left" Margin="50,138,0,0" Name="labelStudentEmail" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentEmail}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,141,0,0" Name="textBoxStudentEmail" VerticalAlignment="Top" Width="120" />
        <Label Content="性別" Height="28" HorizontalAlignment="Left" Margin="57,176,0,0" Name="labelStudentSex" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentSex}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,180,0,0" Name="textBoxStudentSex" VerticalAlignment="Top" Width="120" />
        <Button Command="{Binding ShowCommand}" Content="顯示" Height="23" HorizontalAlignment="Left" Margin="345,27,0,0" Name="buttonShow" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

MainWindow.xaml的后端代碼如下所示。

using System.Windows;
using WPFMVVMExample.ViewModel;
 
namespace WPFMVVMExample
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new StudentViewModel();
        }
    }
}

5 運行程序

運行程序,點擊“顯示”按鈕,即將數據綁定至界面顯示。

 

 

6 說明

WPF中使用MVVM可以降低UI顯示與后端邏輯代碼的耦合度,即更換界面時,只需要修改很少的邏輯代碼就可以實現,甚至不用修改。

在WinForm開發中,我們一般會直接操作界面的元素(如:TextBox1.Text=“aaa”),這樣一來,界面變化后,后端邏輯代碼也需要做相應的變更。

在WPF中使用數據綁定機制,當數據變化后,數據會通知界面變更的發生,而不需要通過訪問界面元素來修改值,這樣在后端邏輯代碼中也就不必操作或者很少操作界面的元素了。

使用MVVM,可以很好的配合WPF的數據綁定機制來實現UI與邏輯代碼的分離,MVVM中的View表示界面,負責頁面顯示,ViewModel負責邏輯處理,包括准備綁定的數據和命令,ViewModel通過View的DataContext屬性綁定至View,Model為業務模型,供ViewModel使用。

 

原文地址:https://blog.csdn.net/yl2isoft/article/details/20838149


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM