Silverlight/WPF/Windows Phone 開發之MVVM設計模式之入門

來源:互聯網
上載者:User
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、運行一下程式,看看效果吧。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.