内容摘要
这一讲,我在原先一篇博客文章(http://www.cnblogs.com/chenxizhang/archive/2011/10/01/2197786.html)基础上,针对MVVM中Command的使用做了演示和讲解。灵活的数据绑定,和命令绑定,是MVVM的核心精神,善加这两个功能,将大大地简化我们的应用程序开发,提供更加合理的代码架构。可以这么说,如果你在做WPF,Silverlight或者相关的开发,你是必须要了解MVVM的。但是至于你使用具体哪一个框架,倒不是那么重要的,他们基本都很类似。
视频地址
http://www.tudou.com/programs/view/SZXSes10MD0/
示例代码
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);
});
}
}
}
}
<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>