MainViewMode里面继承的ViewModelBase
Nuget获得MvvmLight
public abstract class ViewModelBase : ObservableObject, ICleanup
ViewModeBase
继承了ObservableObject
,转到ObservableObject
定义
public class ObservableObject : INotifyPropertyChanged
框架里面ObservableObject
继承接口INotifyPropertyChanged
,接口里有一个重要的事件RaisePropertyChanged
,这和系统里INotifyPropertyChanged
里面的事件PropertyChanged
是一样的。
public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null);
public virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression);
代码详解
Xaml
<Window x:Class="WpfTest.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:WpfTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBox Text="{Binding Name}" />
<TextBox Text="{Binding Title}"/>
<Button Height="50" Content="Show" Command="{Binding ShowCommand}"/>
</StackPanel>
</Grid>
</Window>
MainViewModel
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfTest
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
Name = "Hello";
ShowCommand = new RelayCommand(Show);
}
public RelayCommand ShowCommand { set; get; }
private string name;
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged();
}
}
private string title;
public string Title
{
get { return title; }
set { title = value;
RaisePropertyChanged();
}
}
public void Show() {
Name = "点击了按钮";
Title = "点击了按钮";
MessageBox.Show(Name);
}
}
}
如第22行,RelayCommand
继承了ICommand
,除了拿到ICommand
两个成员函数,一个事件以外,RelayCommand
还声明了RelayCommand
,RelayCommand
是一个可以接受泛型的类型,可以用于接受方法,将方法传递给ICommand
里面的执行函数。
巧用RelayCommand
目标:在TextBox
里输入值,点击Button
,对话框显示TextBox
里的值。
分析:
-
点击
Button
时,弹出的对话框一定是用了Message.Show()
,而Button
用了方法,可以想到用一个RelayCommand
类型的属性接受,然后再在Xaml
里用Command
去绑定这个属性。 -
Button
里面Command
接收RelayCommand
,RelayCommand
是泛型,它的构造函数的参数是泛型委托,它有两个特点,一是它的参数类型是委托,二是可以指定委托的方法里面的参数类型。 -
Command
里面包裹着参数,意味着,Command里面可以再传参数的,他有个CommandParameter,也可以实现绑定,当用他绑定TextBox
里面的Text
时,意味着传进了string参数。 -
因此
RelayCommand
的泛型要写为public RelayCommand<string> ShowCommand { set; get; }
-
Show
方法相应变为
public void Show(string content) {
Name = "点击了按钮";
Title = "点击了按钮";
MessageBox.Show(content);