wpf入门之mvvmlight初体验

13 篇文章 1 订阅

双向绑定是wpf的一大特色,甚至android都开始争相模仿,其中mvvmlight又是mvvm的一个典型代表库,节省了好多onpropertychanged例行代码,本文简单介绍一下数据的双向绑定以及控件方法的绑定,效果就是打开窗口,文本里显示666,点击按钮后变成777,很简单,也是很重要的基础。

1、首先,从nuget引入mvvmlight包,如图,不用怀疑,第一个就是最常用的 ,直接下载安装。

2、安装完毕后,会在解决方案里出现ViewModel文件夹,里面有两个cs文件,MainViewModel.cs和ViewModelLocator.cs(这个没什么用,可以删除)。

3、MainViewModel.cs里就是我们要用到的viewmodel内容了,可以在里面写入属性以及方法的代码,如下:

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace WpfApp8.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            Name = "666";
            Command = new RelayCommand(() => {
                Name = "777";
            });
        }


    

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                RaisePropertyChanged("Name");
            }
        }
    
 
        public RelayCommand Command { get ; set ; }
    }
}

4、然后在mian主窗口实例化MainViewModel,就可以用这个viewmodel类了

  this.DataContext = new ViewModel.MainViewModel ();

5、最后在前端也就是xaml里直接使用viewmodel里的属性名称,就可以了

<Window x:Class="WpfApp8.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:WpfApp8"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="160,141,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="120"/>
        <Button Command="{Binding Command}" Content="Button" HorizontalAlignment="Left" Margin="303,144,0,0" VerticalAlignment="Top" Width="75"/>

    </Grid>
</Window>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值