內容摘要
這一講,我在原先一篇博客文章(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>