在windows phone 上做过应用的童鞋们基本上都知道 MVVM Light框架, MVVM Light实现了将页面和cs抽离,IOC,以及消息系统。
Command 大家在做WP应用的时候肯定用的非常多,例如button点击事件Command等等。
那Command如果要我们实现,该如何去做呢?
Command起初是设计模式中一个很重要也是十分好用的一个模式。 想了解请参考 http://en.wikipedia.org/wiki/Command_pattern
SilverLight中定义了一个ICommand接口,该接口即为Command pattern的一个实现,接口定义如下:
ICommand成员函数如下:
1.CanExecute(object parameter) 用来确定Comand是否可以执行
2.CanExecuteChanged 事件用来通知使用这个Command控件当前的Command状态改变
3.Execute(object parameter) 执行特定的行为
示例代码:
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace WpfMVVM
{
public class MainWindowViewModel:ViewModelBase
{
private string _UserName;
public string UserName
{
get { return _UserName; }
set
{
if (_UserName != value)
{
_UserName = value;
RaisePropertyChanged("UserName");
}
}
}
public ICommand ShowCommand
{
get
{
return new RelayCommand<string>(
(user) =>
{
MessageBox.Show(user);
}, (user) => {
return !string.IsNullOrEmpty(user);
});
}
}
}
}
xaml绑定:
<Window x:Class="WpfMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
xmlns:local="clr-namespace:WpfMVVM"
Height="350"
Width="525">
<Window.DataContext>
<local:MainWindowViewModel UserName="chenxizhang"></local:MainWindowViewModel>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBox Text="{Binding UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Button Content="Show"
Command="{Binding ShowCommand}"
CommandParameter="{Binding UserName}"></Button>
</StackPanel>
</Grid>
</Window>
提示:为了能使绑定事件的处理方法里能够调用到xaml页面的控件参数,最好把相关控件参数动态双向绑定到一个Model。在需要时,可以直接调用该Model的属性获取参数。