C# WPF MVVM框架搭建

至于啥是MVVM在此不再赘述,可以参考这位大神写的博客 : http://www.cnblogs.com/durow/p/4853729.html

在此只是搭建一个简单的框架, 仅供学习参考, 欢迎转载. 如有任何问题,意见或建议欢迎随时批评指正.

如有侵权请及时联系删除,谢谢.

包含的基础类参考如下截图,具体类的作用我会随着代码展开做简短的解释.

C# WPF MVVM框架搭建

类图参考:

C# WPF MVVM框架搭建

首先我创建了三个文件夹进行管理,分别为Controller(绑定的属性管理,命令管理),Model(绑定的属性)和View(UI).

基础类原码:

BaseController.cs   (各Controller的一个基类)  ↓

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVVM.App.Control
{
    public class BaseController
    {
        public BaseController(CNotifyPropertyChange model)
        {
            m_model = model;
        }
        private CNotifyPropertyChange m_model = null;
        public CNotifyPropertyChange Model
        {
            get { return m_model; }
        }
    }
}

DelegateCommand.cs  (命令绑定实现类) ↓

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MVVM.App.Control
{
    #pragma warning disable 0067
    public class DelegateCommand : ICommand
    {
        public Func<object, bool> canExecute;
        public Action<object> executeAction;
        public bool canExecuteCache;

        public DelegateCommand()
        {
           
        }

        public bool CanExecute(object parameter)
        {
            if (null != parameter)
            {
                Type type = parameter.GetType();
                if ("System.Windows.Controls.Slider" == type.ToString())
                {
                    System.Windows.Controls.Slider slider = (System.Windows.Controls.Slider)parameter;
                    if (slider.IsMouseCaptureWithin || slider.IsKeyboardFocusWithin)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return true;

        }
        public event EventHandler CanExecuteChanged;
      
        public void Execute(object parameter)
        {
            executeAction(parameter);
        }


       
    }
}

CNotifyPropertyChange.cs  (主要封装了绑定的属性改变时的通知函数) ↓

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace MVVM.App.Control
{
    public class CNotifyPropertyChange : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }
        }
    }
}

除了上述基类或同一管理的类,下面就是具体的实现类了:

我在UI上拖了一个Button

<Button Content="Button" HorizontalAlignment="Left" Margin="246,59,0,0" VerticalAlignment="Top" Width="75" Background="AliceBlue"/>

如何将这个Button的某些属性和命令通过MVVM实现呢?

首先我前台的数据绑定在后台的哪个地方? -> 此框架中所有数据都在ViewModel.cs中进行管理,因此要将窗口的DataContext设置到类ViewModel的实例化中,参考以下代码:

UserInterface.xaml.cs    ↓

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MVVM.App.TM
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UserInterface : Window
    {
        private ViewModel m_viewModel = null;
        public UserInterface()
        {
            m_viewModel = new ViewModel();
            this.DataContext = m_viewModel;
            InitializeComponent();
        }
    }
}

ViewModel中可以自己实现绑定的属性,但是为了管理方便,在此我聚合了一个UIModel, 这样做的好处是大型的项目中UI经常分为好几个模块进行管理,也就是多个Model. 每个Model应该有个Controller进行属性的管理, Controller也应该聚合在ViewModel中.

ViewModel.cs   ↓

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using MVVM.App.Control;

namespace MVVM.App.TM
{
    
    class ViewModel : CNotifyPropertyChange
    {
        public UIModel m_UIModel { get; set; }
        public UIController m_UIController { get; set; }

        public ViewModel()
        {
            try
            {
                m_UIModel = new UIModel();
                if (m_UIController == null)
                {
                    m_UIController = new UIController(m_UIModel);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}

我想要通过MVVM模式改变这个Button的Content, 需要将Content="Button"改为Content="{Binding m_UIModel.strContext,UpdateSourceTrigger=PropertyChanged}"

strContext是啥呢?就是我要这个Button的Content绑定的字符串

UpdateSourceTrigger=PropertyChanged啥意思呢?就是当这个字符串改变时麻烦让这个函数通知下UI

<Button Content="{Binding m_UIModel.strContext,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="246,59,0,0" VerticalAlignment="Top" Width="75" Background="AliceBlue" />

OK,那UIModel应该怎么写呢?很简单搞两个字符串,一个对内一个对外,注意当外部让这个字符串改变时别忘了调用this.NotifyPropertyChange("strContext")这个函数,每次改变都会去前台找谁绑定了"strContext",然后做出改变

UIModel.cs   ↓

using MVVM.App.Control;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MVVM.App.TM
{
    class UIModel : CNotifyPropertyChange
    {
        public UIModel()
        {

        }

        private string m_strContext;
        public string strContext
        {
            get { return m_strContext; }
            set
            {
                m_strContext = value;
                this.NotifyPropertyChange("strContext");
            }
        }
    }
}

OK,那strContext在哪里管理呢?当然是类UIController里面了

比如说我设置一个初始值,点开窗口Button的Content为"Hello",Controller里面在构造函数里面控制一下就行了:

UIController.cs  ↓

using MVVM.App.Control;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MVVM.App.TM
{
    class UIController : BaseController
    {
        public UIController(CNotifyPropertyChange model) : base(model)
        {
            ((UIModel)(this.Model)).strContext = "Hello";
        }

    }
}

好,这个时候一个属性绑定已经完成了,运行结果如下:

C# WPF MVVM框架搭建

好,接着搞,我想点击这个Button后让这个Button的Content变成WPF,再点击又变成Hello......

这个时候就用到命令绑定了

需要在Button的Grid里面加上这么一段话:Command="{Binding m_UIController.btn_Clicked}"   ↓

<Button Content="{Binding m_UIModel.strContext,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="246,59,0,0" VerticalAlignment="Top" Width="75" Background="AliceBlue" Command="{Binding m_UIController.btn_Clicked}"/>

btn_Clicked是一个命令,实际就是DelegateCommand,继承于ICommand

btn_Clicked直接在UIController里面实现就可以了,因此添加如下代码:

UIController.cs  ↓

using MVVM.App.Control;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MVVM.App.TM
{
    class UIController : BaseController
    {
        public DelegateCommand btn_Clicked { get; set; }
        public UIController(CNotifyPropertyChange model) : base(model)
        {
            btn_Clicked = new DelegateCommand();
            btn_Clicked.executeAction = new Action<object>(btnClicked);
            ((UIModel)(this.Model)).strContext = "Hello";
        }
        private void btnClicked(object obj)
        {
            if ("Hello" == ((UIModel)(this.Model)).strContext)
            {
                ((UIModel)(this.Model)).strContext = "WPF";
            }
            else
            {
                ((UIModel)(this.Model)).strContext = "Hello";
            }
        }
    }
}

好,最终效果如下(Sorry,鼠标的轨迹和点击没有被录制上去,但是不影响效果^-^):

C# WPF MVVM框架搭建