MVVM模式---Command与CommandParameter的使用

在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的属性获取参数。



参考: http://www.cnblogs.com/qingci/archive/2012/09/12/2681594.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值