实例学习WPF的MVVM编程模式1
程序员文章站
2022-07-01 19:56:58
...
先看一下程序界面,要实现的功能很简单,输入一个数,然后点击按钮,将输入数的平方根结果显示在上方。
不使用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>
- 完整代码链接
https://download.csdn.net/download/u012366767/10620072