例項學習WPF的MVVM程式設計模式1
阿新 • • 發佈:2019-01-22
先看一下程式介面,要實現的功能很簡單,輸入一個數,然後點選按鈕,將輸入數的平方根結果顯示在上方。
不使用MVVM模式,在Calculate按鈕的Click事件中,編寫程式碼,將結果顯示到上方的TextBlock中。
現在,我們來一步步實現MVVM模式程式設計,將
- 資料屬性:ViewModel的基類NotificationObject.cs,ViewModel屬性改變,通過Binding去改變介面;
using System.ComponentModel; namespace MVVMDemo1.ViewModels { class NotificationObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (propertyName != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } }
- 命令屬性:DelegateCommand.cs;
using System; using System.Windows.Input; namespace MVVMDemo1.Commands { class DelegateCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { if (CanExecuteFunc == null) { return true; } return CanExecuteFunc(parameter); } public void Execute(object parameter) { if (ExecuteAction == null) { return; } ExecuteAction(parameter); } public Action<object> ExecuteAction { get; set; } public Func<object, bool> CanExecuteFunc { get; set; } } }
- 主窗體的ViewModel:MainWindowViewModel.cs
using MVVMDemo1.Commands; using System; namespace MVVMDemo1.ViewModels { class MainWindowViewModel: NotificationObject { private string result; public string Result { get { return result; } set { result = value; RaisePropertyChanged("Result"); } } private double number; public double Number { get { return number; } set { number = value; RaisePropertyChanged("Number"); } } public DelegateCommand CalculateSquareRootCommand { get; set; } private void CalculateSquareRoot(object parameter) { Result = "Square Root of " + Number.ToString() + " is " + string.Format("{0:F4}", Math.Sqrt(Number)); } public MainWindowViewModel() { CalculateSquareRootCommand = new DelegateCommand { ExecuteAction = new Action<object>(CalculateSquareRoot) }; } } }
- 主窗體xaml檔案
<Window x:Class="MVVMDemo1.MainWindow"
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:local="clr-namespace:MVVMDemo1.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="150" Width="300">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBlock Text="{Binding Result}" Margin="5,50,5,5"/>
<StackPanel Orientation="Horizontal" Margin="5">
<Label Content="Number:" Margin="5"/>
<TextBox Text="{Binding Number}" Width="100" Margin="5" VerticalContentAlignment="Center"/>
<Button Content="Calculate" Margin="5" Command="{Binding CalculateSquareRootCommand}"/>
</StackPanel>
</StackPanel>
</Grid>
</Window>
- 完整程式碼連結