码迷,mamicode.com
首页 > 其他好文 > 详细

MVVM学习笔记

时间:2016-08-06 19:07:28      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

MVVM学习笔记

1、MVVM的简介

 MVVM模式是Model-View-ViewModel模式的简称,也就是由模型(Model)、视图(View)、视图模型(ViewModel),其目的是为了实现将业务和界面分开,降低耦合度。

2、示例(绑定TextBoxCombox控件)

总体结构:

技术分享

 

View层代码:

技术分享
        <Label Content="购买数:"
               Style="{StaticResource LabStyle}"
               Grid.Row="3"
               Grid.Column="0" />
        <TextBox Grid.Row="3"
                 Grid.Column="1"
                 Style="{StaticResource TextBoxStyle}"
                 Text="{Binding BuyTextBox,UpdateSourceTrigger=PropertyChanged}">
        </TextBox>

 <ComboBox Grid.Row="0"
                  Grid.Column="1"
                  Style="{StaticResource ComboxStyle}">
            <ComboBoxItem Content="西瓜" />
        </ComboBox>
        <ComboBox Grid.Row="1"
                  Grid.Column="1"
                  Style="{StaticResource ComboxStyle}"
                  ItemsSource="{Binding Prices}"
                  SelectedItem="{Binding SelectPrice, UpdateSourceTrigger=PropertyChanged}">
        </ComboBox>
View Code

 

ViewModel层代码

技术分享
   /// <summary>
        /// 设置购买量属性
        /// </summary>
        public int BuyTextBox
        {
            get { return m_buyNum; }
            set
            {
                m_buyNum = value;
                //计算金额
                m_money = m_selectPrice*m_buyNum;
                if (m_buyNum > m_surplus)
                {
                    MessageBox.Show("购买数量大于剩余数量,请重新输入购买数量!");
                    m_buyNum = 0;
                    m_money = 0;
                }
                OnPropertyChange<CalculateFruitVm>(vm => vm.BuyTextBox);
            }
        }
View Code

 

技术分享
    /// <summary>
        /// 设置价格属性
        /// </summary>
        public ObservableCollection<int> Prices
        {
            get { return m_prices; }
            set
            {
                m_prices = value;
                OnPropertyChange<CalculateFruitVm>(vm => vm.Prices);
            }
        }
View Code

 

技术分享
 /// <summary>
        /// 设置选择价格属性
        /// </summary>
        public int SelectPrice
        {
            get { return m_selectPrice; }
            set
            {
                m_selectPrice = value;
                m_money = m_selectPrice*m_buyNum;
                OnPropertyChange<CalculateFruitVm>(vm => vm.SelectPrice);
            }
        }
View Code

 

技术分享
  /// <summary>
        /// 构造函数CalculateFruitVm
        /// </summary>
        public CalculateFruitVm()
        {
            m_prices.Add(4);
            m_selectPrice = 4;
            m_prices.Add(5);
        }
View Code

 

注意:这里是在构造函数CalculateFruitVm中设置价格并选择价格,因价格是combox控件,除了需要设置价格属性外,还需要设置价格选择属性。

Button按钮

View层代码

技术分享
            <Button Content="返回"
                    Grid.Column="2"
                    Style="{StaticResource ButtonStyle}"
                    HorizontalAlignment="Left"
                    Command="{Binding CancleCommand}"></Button>
View Code

 

ViewModel层代码

技术分享
        /// <summary>
        /// CancleCommand命令
        /// </summary>
        public ICommand CancleCommand
        {
            get { return m_cancelCommand; }
        }
View Code

 

技术分享
        /// <summary>
        /// 构造函数CalculateFruitVm
        /// </summary>
        public CalculateFruitVm()
        {
            m_cancelCommand = ICommandFactory.CreateCommand(CancelCmdExecute, CanCancelCmdExecute);
        }
View Code

 

技术分享
        /// <summary>
        /// 声明CancelEvent事件
        /// </summary>
        public event EventHandler<EventArgs> CancelEvent;
        /// <summary>
        /// CanCancelCmdExecute事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private bool CanCancelCmdExecute(object arg)
        {
            return true;
        }
View Code

 

技术分享
        /// <summary>
        /// CancelCmdExecute事件
        /// </summary>
        /// <param name="obj"></param>
        private void CancelCmdExecute(object obj)
        {
            if (CancelEvent != null)
            {
                CancelEvent(this, EventArgs.Empty);
            }
        }
View Code

 

.xaml.cs代码

技术分享
  public CalculateFruit()
        {
            InitializeComponent();
            CalculateFruitVm calculateFruitVm = new CalculateFruitVm();
            DataContext = calculateFruitVm;
            calculateFruitVm.CancelEvent += calculateFruitVm_CancelEvent;
        }
View Code

 

技术分享
        /// <summary>
        /// 点击返回按钮,返回主界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void calculateFruitVm_CancelEvent(object sender, EventArgs e)
        {
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
            this.Hide();
        }
View Code

 

Button按钮需要在View层用command绑定事件,ViewModel中创建命令、构造函数、声明事件,最后在.xaml.cs中加载ViewModel,并实现界面跳转、关闭等操作。

3、总结

 MVVM 中更好的实现了面向对象中的继承和封装,所有的命令都继承自ICommand接口,将所有的命令用ViewModel层去实现。

当界面之间需要互相传值时,需要在VM中传递界面需要的值,实例化需要传到哪个界面的VM,示例如下:

隐藏事件

技术分享
   private void HideCmdExecute(object obj)
        {
            if (m_buyNum > 0 && m_selectPrice > 0)
            {
                if (HideEvent != null)
                {
                    //计算剩余量
                    m_surplus -= m_buyNum;
                    //计算售卖总量
                    CalculateNum += m_buyNum;
                    //计算售卖总金额
                    CalculateMoney += m_money;
                    //new出ResultCalculateVm并赋值
                    ResultCalculateVm resultCalculateVm = new ResultCalculateVm();
                    resultCalculateVm.SalesNumberTextBox = CalculateNum;
                    resultCalculateVm.TotalMoney = CalculateMoney;
                    resultCalculateVm.TotalSurplus = m_surplus;
                    HideEvent(this, new FruitEventArgs {ResultCalculateVm = resultCalculateVm});
                }
            }           
        }
View Code

 

MVVM学习笔记

标签:

原文地址:http://www.cnblogs.com/xiangyueqiaomai/p/5744560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!