C# WPF MVVM框架搭建

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

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

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

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

类图参考:

首先我创建了三个文件夹进行管理,分别为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";
        }

    }
}

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

好,接着搞,我想点击这个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,鼠标的轨迹和点击没有被录制上去,但是不影响效果^-^):

Gif

 

 

  • 10
    点赞
  • 96
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,下面是一个简单的 WPF MVVM 框架搭建的工程事例: 1. 创建一个 WPF 应用程序项目。 2. 在项目中添加一个名为 Models 的文件夹,并在其中添加一个名为 Student.cs 的类,该类包含学生的姓名和年龄属性: ```csharp namespace WpfMvvmDemo.Models { public class Student { public string Name { get; set; } public int Age { get; set; } } } ``` 3. 在项目中添加一个名为 ViewModels 的文件夹,并在其中添加一个名为 MainViewModel.cs 的类,该类包含一个名为 Students 的可观察集合属性,用于存储学生对象,并在构造函数中初始化该集合: ```csharp using System.Collections.ObjectModel; using WpfMvvmDemo.Models; namespace WpfMvvmDemo.ViewModels { public class MainViewModel { public ObservableCollection<Student> Students { get; set; } public MainViewModel() { Students = new ObservableCollection<Student> { new Student { Name = "张三", Age = 18 }, new Student { Name = "李四", Age = 19 }, new Student { Name = "王五", Age = 20 } }; } } } ``` 4. 在项目中添加一个名为 Views 的文件夹,并在其中添加一个名为 MainWindow.xaml 的窗口。 5. 在 MainWindow.xaml 中,将窗口的 DataContext 属性设置为 MainViewModel 的实例,并使用 ItemsControl 控件绑定到 MainViewModel 中的 Students 属性: ```xaml <Window x:Class="WpfMvvmDemo.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfMvvmDemo.Views" xmlns:viewModel="clr-namespace:WpfMvvmDemo.ViewModels" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.DataContext> <viewModel:MainViewModel /> </Window.DataContext> <Grid> <ItemsControl ItemsSource="{Binding Students}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}" Margin="5" /> <TextBlock Text="{Binding Age}" Margin="5" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Window> ``` 6. 运行项目,可以看到窗口中显示了三个学生的姓名和年龄。 这就是一个简单的 WPF MVVM 框架搭建的工程事例。当然,这只是一个最基础的框架,实际开发中还需要考虑很多其他方面的问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值