wpf mvvm模式 实例

图例:

 

 

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 (接收两个参数(都是委托),分别告诉它‘做什么’,‘什么情况下可以做’如果用了prism则不需要自己写
   这个类)
    /// </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(同delegateCommand一样,如果引用了prism,则不需要自定义此类,在此只是为了说明它的实现方式s)
    /// </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(this, new 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
{
 
负责与VIEW通信的VIEWMODEL类,提供给VIEW双向绑定的属性和一些事件触发的COMMAND,例如单击一个按钮要执行的操作
可以包在DelegateCOMMAND,在view层绑定就可以了

    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:

 

 VIEW层,这里只提供展示的代码以及绑定的逻辑,注意记得引入VM所在的路径

 

<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>


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值