Silverlight/WPF/Windows Phone 开发之MVVM设计模式之入门

简介: 1、新建一个WPF、Silverlight或Windows Phone的项目。2、在项目中新建几个文件夹,Models、Views、ViewModels、Data、Service、Commands。
1、新建一个WPF、Silverlight或Windows Phone的项目。

2、在项目中新建几个文件夹,Models、Views、ViewModels、Data、Service、Commands。

3、在ViewModels文件夹中新建一个NotificationObject.cs类,代码如下:

    public class NotificationObject:INotifyPropertyChanged
    {
        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

4、在Commands文件夹中新建一个DelegateCommand.cs命令类,代码如下:
    public class DelegateCommand : ICommand
    {
        #region ICommand 成员
		public Action<object> ExecuteAction { get; set; }
        public Func<object, bool> CanExecuteFunc { get; set; }

        public bool CanExecute(object parameter)
        {
            if (this.CanExecuteFunc == null)
            {
                return true;
            }
            return this.CanExecuteFunc(parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (this.ExecuteAction == null)
            {
                return;
            }
            this.ExecuteAction(parameter);
        }
        #endregion
    }

5、在Data文件夹下新建一个xml文件,Data.xml,内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student>
    <Name>张三</Name>
    <Age>25</Age>
    <Sex>男</Sex>
    <Job>IT开发工程师</Job>
  </Student>
    <Student>
    <Name>李四</Name>
    <Age>26</Age>
    <Sex>女</Sex>
    <Job>销售经理</Job>
  </Student>
</Students>

6、在Models文件夹下,新建一个Student.cs类,代码如下:
    public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public string Sex { get; set; }
        public string Job { get; set; }
    }

7、在Services文件下,新建一个IDataService.cs接口文件,代码如下:
    public interface IDataService
    {
        List<Student> GetAllStudents();
    }
  还有一个XmlDataService.cs读取xml的类,用来实现以上接口,代码如下:
    public class XmlDataService : IDataService
    {
        #region IDataService 成员

        public List<Student> GetAllStudents()
        {
            List<Student> studentList = new List<Student>();
            string xmlFileName = System.IO.Path.Combine(Environment.CurrentDirectory, @"Data\Data.xml");
            XDocument document = XDocument.Load(xmlFileName);
            var students = document.Descendants("Student");
            foreach (var stu in students)
            {
                Student studnet = new Student();
                studnet.Name = stu.Element("Name").Value;
                studnet.Age = stu.Element("Age").Value;
                studnet.Sex = stu.Element("Sex").Value;
                studnet.Job = stu.Element("Job").Value;
                studentList.Add(studnet);
            }
            return studentList;
        }

        #endregion
    }

8、在ViewModels文件夹下,新建一个StudentItemViewModel.cs类,代码如下:
    class StudentItemViewModel:NotificationObject
    {
        public Student Student { get; set; }

        private bool _isSelected;

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                this.RaisePropertyChanged("IsSelected");
            }
        }
    }
在新建一个类,StudentViewModel.cs,代码如下:
    class StudentViewModel : NotificationObject
    {
		//命令属性
        public DelegateCommand SelectStudentItemCommand { get; set; }

		//数据属性,用来统计选中多少学生
        private int _count;

        public int Count
        {
            get { return _count; }
            set
            {
                _count = value;
                this.RaisePropertyChanged("Count");
            }
        }

        private Student _student;

        public Student Student 
        {
            get { return _student; }
            set
            {
                _student = value;
                this.RaisePropertyChanged("Student");
            }
        }

        private List<StudentItemViewModel> _studentList;

        public List<StudentItemViewModel> StudentList
        {
            get { return _studentList; }
            set
            {
                _studentList = value;
                this.RaisePropertyChanged("StudentList");
            }
        }

        public StudentViewModel()
        {
            this.LoadStudentList();
            this.SelectStudentItemCommand = new DelegateCommand(new Action(this.SelectStudentItemCommandExecute));
        }

        void LoadStudentList()
        {
            XmlDataService ds = new XmlDataService();
            var students = ds.GetAllStudents();
            this.StudentList = new List<StudentItemViewModel>();
            foreach (var student in students)
            {
                StudentItemViewModel item = new StudentItemViewModel();
                item.Student = student;
                this.StudentList.Add(item);
            }
        }

        private void SelectStudentItemCommandExecute()
        {
            this.Count = this.StudentList.Count(p=>p.IsSelected==true);
        }
    }


9、在Views文件夹下,新建一个Student.xaml,内容如下:
     <Grid>
        <DataGrid AutoGenerateColumns="False" CanUserAddRows="False"  ItemsSource="{Binding StudentList}"  CanUserDeleteRows="False" Height="138" HorizontalAlignment="Left" Margin="10,82,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="256">
            <DataGrid.Columns>
                <DataGridTextColumn Header="姓名" Binding="{Binding Student.Name}" Width="50"></DataGridTextColumn>
                <DataGridTextColumn Header="年龄" Binding="{Binding Student.Age}" Width="50"></DataGridTextColumn>
                <DataGridTextColumn Header="性别" Binding="{Binding Student.Sex}" Width="50"></DataGridTextColumn>
                <DataGridTextColumn Header="工作" Binding="{Binding Student.Job}" Width="50"></DataGridTextColumn>
                <DataGridTemplateColumn Header="选中" SortMemberPath="IsSelected">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding Path=IsSelected,UpdateSourceTrigger=PropertyChanged}" Command="{Binding Path=DataContext.SelectStudentItemCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}">
                            </CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="21,238,0,0" Name="textBlock7" Text="共选中:" VerticalAlignment="Top" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="75,238,0,0" Name="textBlock8" Text="{Binding Count}" VerticalAlignment="Top" />
    </Grid>

	public partial class Student : Window
    {
        public Student()
        {
            InitializeComponent();
            this.DataContext = new StudentViewModel();
        }
    }

10、在App.xaml中设置起始页
<Application x:Class="WPFDemo2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Views/Student.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

11、运行一下程序,看看效果吧。


相关文章
|
6月前
|
设计模式 消息中间件 算法
现货期权交易所开发模块化设计模式
现货期权交易所模块化设计通过解耦核心系统,构建契约化接口与清晰边界,提升迭代效率与容错能力。涵盖行情、撮合、风控等模块,支持独立部署、灰度发布与跨团队协同,降低开发成本,增强可扩展性与可观测性,助力高并发场景下的稳定运行与快速响应。
|
设计模式 安全 数据库连接
后端开发中的设计模式应用
在软件开发的浩瀚海洋中,设计模式如同灯塔,为后端开发者指引方向。它们不仅仅是代码的模板,更是解决复杂问题的智慧结晶。本文将深入探讨几种常见的设计模式,包括单例模式、工厂模式和观察者模式,并揭示它们在实际应用中如何提升代码的可维护性、扩展性和重用性。通过实例分析,我们将一窥这些模式如何在后端开发中大放异彩,助力构建高效、灵活的软件系统。
|
设计模式 算法 搜索推荐
后端开发中的设计模式应用与实践
在软件开发的广袤天地中,后端技术如同构筑高楼大厦的钢筋水泥,支撑起整个应用程序的骨架。本文旨在通过深入浅出的方式,探讨后端开发领域内不可或缺的设计模式,这些模式犹如精雕细琢的工具箱,能够助力开发者打造出既健壮又灵活的系统架构。从单例模式到工厂模式,从观察者模式到策略模式,每一种设计模式都蕴含着深刻的哲理与实践价值,它们不仅仅是代码的组织方式,更是解决复杂问题的智慧结晶。
|
设计模式 Java
【设计模式】工厂模式(定义 | 特点 | Demo入门讲解)
【设计模式】工厂模式(定义 | 特点 | Demo入门讲解)
456 2
|
设计模式 算法 搜索推荐
后端开发中的设计模式应用
在软件开发的浩瀚海洋中,设计模式犹如一座座灯塔,为后端开发者指引方向。本文将深入探讨后端开发中常见的设计模式,并通过实例展示如何在实际项目中巧妙应用这些模式,以提升代码的可维护性、扩展性和复用性。通过阅读本文,您将能够更加自信地应对复杂后端系统的设计与实现挑战。
307 3
|
设计模式 XML Java
【设计模式】装饰器模式(定义 | 特点 | Demo入门讲解)
【设计模式】装饰器模式(定义 | 特点 | Demo入门讲解)
177 0
|
设计模式 传感器
【设计模式】观察者模式(定义 | 特点 | Demo入门讲解)
【设计模式】观察者模式(定义 | 特点 | Demo入门讲解)
264 0
|
设计模式 算法 搜索推荐
后端开发中的设计模式应用
在软件开发的浩瀚海洋中,设计模式犹如灯塔一般指引着方向。它们不是一成不变的规则,而是前人智慧的结晶。本文将深入探讨几种在后端开发中常用的设计模式,如单例、工厂、观察者和策略模式,并阐述如何在实际项目中灵活运用这些模式来提升代码质量、可维护性和扩展性。通过对比传统开发方式与应用设计模式后的差异,我们将揭示设计模式在解决复杂问题和优化系统架构中的独特价值。
|
设计模式 JavaScript Java
后端开发中的设计模式应用
本文将深入探讨后端开发中常见的设计模式,包括单例模式、工厂模式和观察者模式。每种模式不仅会介绍其定义和结构,还会结合实际案例展示如何在后端开发中应用这些模式来优化代码的可维护性与扩展性。通过对比传统方法与设计模式的应用,读者可以更清晰地理解设计模式的优势,并学会在项目中灵活运用这些模式解决实际问题。
|
设计模式 C# 开发者
C#设计模式入门实战教程
C#设计模式入门实战教程
213 3