.net中创建一个简单的MVVM项目(1)

使用WPF开发应用程序,MVVM也许是个绕不过去的东西了,做一个小程序,做个参考。

MVVM是Model-View-ViewModel的简写,代码分离真是做的相当到位,通过界面和控制类中的数据绑定,来实现数据的展示。

第一步,建立view和viewmodel的联系。

1.新建WPF应用程序。

2.添加viewmodel文件夹,新建一个viewmodel的类,初始化的时候,实例化主窗口。

MainWindow Mw = new MainWindow();

3.修改app.xaml中项目的启动方式,使用startup事件,实例化viewmodel。

MainWindowViewModel Mw = new MainWindowViewModel();

第二步,view的数据绑定。

1.viewmodel中添加属性,然后设置view的数据上下文,最后,显示view。

public string Name { get; set; }

Name = "hello MVVM";
Mw.DataContext = this;
Mw.ShowDialog();

2.view中要做的就是绑定这个属性,添加一个按钮,content绑定name属性即可。

Button Content="{Binding Name}"

 

这只是一个最简单的展示,数据实体应该存放在model中,这个例子中暂时还没有用到model。

view的代码:

<Window x:Class="MyWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="{Binding Name}" Height="23" HorizontalAlignment="Left" Margin="116,53,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>
MainWindow

viewmodel的代码:

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

namespace MyWPFApp.ViewModel
{
    class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            Initialize();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            MainWindow Mw = new MainWindow();
            Name = "hello MVVM";
            Mw.DataContext = this;
            Mw.ShowDialog();
        }

        #region 属性
        public string Name { get; set; }


        #endregion
    }
}
MainWindowViewModel

app.xaml的代码:

<Application x:Class="MyWPFApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             Startup="Application_Startup">
    <Application.Resources>
         
    </Application.Resources>
</Application>
app.xaml

app.xaml.cs的代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using MyWPFApp.ViewModel;

namespace MyWPFApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            MainWindowViewModel Mw = new MainWindowViewModel();
        }

    }
}
app.xaml.cs

主界面的cs文件中没有添加一行代码,在MVVM模式中,界面要做的只有一个数据的绑定,理论上,界面是相对独立的。

当然,MVVM的绑定并没有这么简单,事件绑定的实现,我以后也会尝试着写写看,理解原理很重要,但是,入门的操作同样也很重要,一步一步来,慢慢的去深入。。。

 

posted @ 2013-09-20 17:15  _倔强  阅读(1791)  评论(10编辑  收藏  举报