博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

wpf mvvm sample

Posted on 2011-05-17 21:00  linFen  阅读(1277)  评论(0编辑  收藏  举报
delegateCommand.cs:

//-----------------------------------------------------------------------
// <copyright file="DelegateCommand.cs" company="Digital China">
//     Copyright (c) Digital China. All rights reserved.
// </copyright>
// <author>Liang Lan</author>
// <date>2011/1/17</date>
//-----------------------------------------------------------------------
namespace selfPro.wpftest.mvvm.Common
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Input;

    /// <summary>
    /// delegate command for view model
    /// </summary>
    public class DelegateCommand : ICommand
    {
        #region members
        /// <summary>
        /// can execute function
        /// </summary>
        private readonly Func<bool> canExecute;

        /// <summary>
        /// execute function
        /// </summary>
        private readonly Action execute;

        #endregion

        /// <summary>
        /// Initializes a new instance of the DelegateCommand class.
        /// </summary>
        /// <param name="execute">indicate an execute function</param>
        public DelegateCommand(Action execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the DelegateCommand class.
        /// </summary>
        /// <param name="execute">execute function </param>
        /// <param name="canExecute">can execute function</param>
        public DelegateCommand(Action execute, Func<bool> canExecute)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        /// <summary>
        /// can executes event handler
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// implement of icommand can execute method
        /// </summary>
        /// <param name="o">parameter by default of icomand interface</param>
        /// <returns>can execute or not</returns>
        public bool CanExecute(object o)
        {
            if (this.canExecute == null)
            {
                return true;
            }

            return this.canExecute();
        }

        /// <summary>
        /// implement of icommand interface execute method
        /// </summary>
        /// <param name="o">parameter by default of icomand interface</param>
        public void Execute(object o)
        {
            this.execute();
        }

        /// <summary>
        /// raise ca excute changed when property changed
        /// </summary>
        public void RaiseCanExecuteChanged()
        {
            if (this.CanExecuteChanged != null)
            {
                this.CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}

notificationObject.cs:

//----------------------------

-------------------------------------------
// <copyright file="NotificationObject.cs" company="Digital China">
//     Copyright (c) Digital China. All rights reserved.
// </copyright>
// <author>Liang Lan</author>
// <date>2011/1/17</date>
//-----------------------------------------------------------------------
namespace selfPro.wpftest.mvvm.Common
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// notification object base class
    /// </summary>
    public abstract class NotificationObject : INotifyPropertyChanged
    {
        /// <summary>
        /// property changed handler
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// raise property changed handler
        /// </summary>
        /// <param name="propertyName">property name to raise</param>
        protected virtual void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(thisnew PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// raise many property changed handler
        /// </summary>
        /// <param name="propertyNames">properties to raise</param>
        protected void RaisePropertyChanged(params string[] propertyNames)
        {
            if (propertyNames == null)
            {
                throw new ArgumentNullException("propertyNames");
            }

            foreach (var name in propertyNames)
            {
                this.RaisePropertyChanged(name);
            }
        }
    }
}

mainwindowViewModel.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using selfPro.wpftest.mvvm.Common;
using System.Windows;

namespace selfPro.wpftest.mvvm.ViewModel
{
    class MainWindowViewModel : NotificationObject
    {
        private string inputStr;

        public string InputStr
        {
            get { return inputStr; }
            set 
            {
                inputStr = value;
                RaisePropertyChanged("InputStr");
            }
        }

        public DelegateCommand CmdRun
        {
            get;
            private set;
        }

        public MainWindowViewModel()
        {
            CmdRun = new DelegateCommand(new Action(Run), new Func<bool>(CanRun));
            this.PropertyChanged += (s, e) => 
            {
                CmdRun.RaiseCanExecuteChanged();
            };
        }

        private bool CanRun()
        {
            if (string.IsNullOrEmpty(InputStr))
            {
                return false;
            }
            return InputStr.Equals("hello world");
        }

        private void Run() 
        {
            MessageBox.Show(InputStr);
        }
    }
}

mainwindow.xaml:

<Window x:Class="selfPro.wpftest.mvvm.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:selfPro.wpftest.mvvm.ViewModel"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:MainWindowViewModel></vm:MainWindowViewModel>
    </Window.DataContext>
    <StackPanel>
        <Button Width="60" Height="24" Content="clickMe" Command="{Binding CmdRun}"/>
        <TextBox Text="{Binding InputStr, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>