Windows Phone 7 MVVM模式通讯方式之实现Command
MVVM模式的View与ViewModel的三大通讯方式:Binding Data(实现数据的传递)、Command(实现操作的调用)和Attached Behavior(实现控件加载过程中的操作)。(1)Windows Phone 7 MVVM模式通讯方式之实现Binding Data。
(2)Windows Phone 7 MVVM模式通讯方式之实现Command。
(3)Windows Phone 7 MVVM模式通讯方式之实现Attached Behavior。
下面通过一个实例实现MVVM模式的Command通讯
(1)MainPage.xaml文件的代码,实现View层
(2)RadiusViewModel.cs文件的代码,实现ViewModel层
using System;
using System.Windows.Input;
using System.ComponentModel;
using Microsoft.Expression.Interactivity.Core;
namespace CommandDemo.ViewModel
{
public class RadiusViewModel : INotifyPropertyChanged
{
private Double radius;
public RadiusViewModel()
{
Radius = 0;
MinRadius = new ActionCommand(p => Radius = 100);
MedRadius = new ActionCommand(p => Radius = 200);
MaxRadius = new ActionCommand(p => Radius = 300);
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand MinRadius
{
get; private set;
}
public ICommand MedRadius
{
get;
private set;
}
public ICommand MaxRadius
{
get;
private set;
}
public Double Radius
{
get
{
return radius;
}
set
{
radius = value;
OnPropertyChanged("Radius");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if(propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
(3)ExecuteCommandAction.cs类,实现Command操作
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Reflection;
namespace CommandDemo.Command
{
public class ExecuteCommandAction : TriggerAction
{
public static readonly DependencyProperty CommandNameProperty =
DependencyProperty.Register("CommandName", typeof(string), typeof(ExecuteCommandAction), null);
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExecuteCommandAction), null);
protected override void Invoke(object parameter)
{
if (AssociatedObject == null)
return;
ICommand command = null;
var dataContext = AssociatedObject.DataContext;
foreach (var info in dataContext.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (IsCommandProperty(info) && String.Equals(info.Name, CommandName, StringComparison.Ordinal))
{
command = (ICommand)info.GetValue(dataContext, null);
break;
}
}
if ((command != null) && command.CanExecute(CommandParameter))
{
command.Execute(CommandParameter);
}
}
private static bool IsCommandProperty(PropertyInfo property)
{
return typeof(ICommand).IsAssignableFrom(property.PropertyType);
}
public string CommandName
{
get
{
return (string)GetValue(CommandNameProperty);
}
set
{
SetValue(CommandNameProperty, value);
}
}
public object CommandParameter
{
get
{
return GetValue(CommandParameterProperty);
}
set
{
SetValue(CommandParameterProperty, value);
}
}
}
}
页:
[1]