Share via


Sample Code-Behind File: WPF Databinding and Entity Framework 4.1

The following WPF code-behind is used in the Tutorial: Creating a Conceptual Model from an Existing Database using Tools (Entity Framework 4.1) walkthrough.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SchoolModelLib;
using System.Data.Entity;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace SchoolModelWPFTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SchoolEntities context = new SchoolEntities();
        private ObservableCollection<OnsiteCourse> _onsiteCourses;
        private ObservableCollection<OnlineCourse> _onlineCourses;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Load is an extension method on IQueryable, defined in the System.Data.Entity namespace.
            // This method enumerates the results of the query, much like ToList but without creating a list. 
            // When used with Linq to Entities this method creates the entity instances and adds to the context.
            context.Departments.Load();
            // After the data is loaded call the DbSet<T>.Local property to use the DbSet<T> as a binding source. 
            this.layoutGrid.DataContext = context.Departments.Local;
        }

        private void comboBoxDepartment_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Department department = this.comboBoxDepartment.SelectedItem as Department;

            if (department != null)
            {
                // Create an instance of the ObservableCollection of the OnsiteCourses type for the selected Department.
                _onsiteCourses = new ObservableCollection<OnsiteCourse>(department.Courses.OfType<OnsiteCourse>());

                // Sign the _onsiteCourses collection up for the NotifyCollectionChangedEventHandler 
                // in order to keep what is in the SchoolEntities context with what is displayed in the ListView in sync. 
                _onsiteCourses.CollectionChanged +=
                    new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_courses_CollectionChanged);

                // Create an instance of the ObservableCollection of the OnlineCourses type for the selected Department.
                _onlineCourses = new ObservableCollection<OnlineCourse>(department.Courses.OfType<OnlineCourse>());

                // Sign the _onlineCourses collection up for the NotifyCollectionChangedEventHandler 
                // in order to keep what is in the SchoolEntities context with what is displayed in the ListView in sync. 
                _onlineCourses.CollectionChanged +=
                    new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_courses_CollectionChanged);

                // Update the content displayed in the ListView controls. 
                this.listViewOnsite.ItemsSource = _onsiteCourses;
                this.listViewOnline.ItemsSource = _onlineCourses;
            }
        }

        private void _courses_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {

            Department department = this.comboBoxDepartment.SelectedItem as Department;
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (Course i in e.NewItems)
                    {
                        // Add a new Course object to the collection of courses 
                        // for the selected department.
                        department.Courses.Add(i);
                    }
                    break;
                case NotifyCollectionChangedAction.Remove:
                    foreach (Course i in e.OldItems)
                    {
                        // Remove a Course object from the context.
                        context.Courses.Remove(i);
                    }
                    break;
            }

        }

        private void buttonAddOnsite_Click(object sender, RoutedEventArgs e)
        {
            Department department = this.comboBoxDepartment.SelectedItem as Department;

            // Generate a new CourseID.
            int newCourseID = department.Courses.Max(c => c.CourseID) + 1;
            
            OnsiteCourse newCourse = new OnsiteCourse()
            {
                CourseID = newCourseID,
                DepartmentID = 0,
                Title = "",
                Credits = 4,
                Location = "",
                Days = "",
                Time = DateTime.Now
            };

            // Add the new object to the ObservableCollection. 
            // This will cause for the _courses_CollectionChanged event handler to be called. 
            _onsiteCourses.Add(newCourse);
        }

        private void buttonDeleteOnsite_Click(object sender, RoutedEventArgs e)
        {
            OnsiteCourse course = this.listViewOnsite.SelectedItem as OnsiteCourse;
            // Remove the selected object from the ObservableCollection. 
            // This will cause for the _courses_CollectionChanged event handler to be called. 
            if (course != null)
                _onsiteCourses.Remove(course);
        }

        private void buttonAddOnline_Click(object sender, RoutedEventArgs e)
        {
            Department department = this.comboBoxDepartment.SelectedItem as Department;

            // Generate a new CourseID.
            int newCourseID = department.Courses.Max(c => c.CourseID) + 1;

            OnlineCourse newCourse = new OnlineCourse()
            {
                CourseID = newCourseID,
                DepartmentID = 0,
                URL = "https://www.",
                Title = "",
                Credits = 4
            };

            // Add the new object to the ObservableCollection. 
            // This will cause for the _courses_CollectionChanged event handler to be called. 
            _onlineCourses.Add(newCourse);
        }

        private void buttonDeleteOnline_Click(object sender, RoutedEventArgs e)
        {
            OnlineCourse course = this.listViewOnline.SelectedItem as OnlineCourse;
            // Remove the selected object from the ObservableCollection. 
            // This will cause for the _courses_CollectionChanged event handler to be called. 
            if (course != null)
                _onlineCourses.Remove(course);
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            // Persist all the change to the database.
            context.SaveChanges();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            context.Dispose();
        }

        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            // Close the form.
            this.Close();
        }
    }
}