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

暖楓無敵發表於2012-04-07
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、執行一下程式,看看效果吧。


相關文章