当前位置: 首页 > news >正文

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>


相关文章:

  • 近期谷歌网页收录数量已经明显超过百度
  • JS操作cookie
  • JS实现拖拽
  • JS显示时间
  • 我开发的一个信息管理小工具——PersonalInfo
  • Oracle字符串字段内的字符排序
  • 创建第一个windows服务
  • jquery的get和post提交
  • 换个思路SQL2005下字符串字段内的字符排序
  • c#委托的异步调用 简单示例
  • c# 索引与迭代器 简单示例
  • Flex与.NET互操作(六):Flex和.NET协同开发利器FluorineFx
  • c# timerCallback小例
  • Flex httpservice返回值类型和处理
  • c# 扩展方法 入门小例
  • canvas 绘制双线技巧
  • co.js - 让异步代码同步化
  • Flex布局到底解决了什么问题
  • iOS 系统授权开发
  • javascript 哈希表
  • JavaScript创建对象的四种方式
  • jdbc就是这么简单
  • 分布式事物理论与实践
  • 类orAPI - 收藏集 - 掘金
  • 力扣(LeetCode)357
  • 如何在 Tornado 中实现 Middleware
  • #if 1...#endif
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • (java)关于Thread的挂起和恢复
  • (rabbitmq的高级特性)消息可靠性
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (附源码)基于SpringBoot和Vue的厨到家服务平台的设计与实现 毕业设计 063133
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (算法)求1到1亿间的质数或素数
  • (五)MySQL的备份及恢复
  • (一) springboot详细介绍
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • .NET / MSBuild 扩展编译时什么时候用 BeforeTargets / AfterTargets 什么时候用 DependsOnTargets?
  • .net core IResultFilter 的 OnResultExecuted和OnResultExecuting的区别
  • .NET Framework 3.5中序列化成JSON数据及JSON数据的反序列化,以及jQuery的调用JSON
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .net 前台table如何加一列下拉框_如何用Word编辑参考文献
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • /使用匿名内部类来复写Handler当中的handlerMessage()方法
  • [ 转载 ] SharePoint 资料
  • [<MySQL优化总结>]
  • [ai笔记4] 将AI工具场景化,应用于生活和工作
  • [ASP.NET 控件实作 Day7] 设定工具箱的控件图标
  • [AX]AX2012 AIF(四):文档服务应用实例
  • [codevs 2822] 爱在心中 【tarjan 算法】
  • [CQOI 2011]动态逆序对
  • [ExtJS5学习笔记]第三十节 sencha extjs 5表格gridpanel分组汇总
  • [FC][常见Mapper IRQ研究]
  • [Golang]K-V存储引擎的学习 从零实现 (RoseDB mini版本)
  • [HNOI2006]鬼谷子的钱袋