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

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、运行一下程序,看看效果吧。


上一篇:Mysql的索引和慢查询优化


下一篇:专注数据中台7年,国云数据要做中国的Snowflake