开发者

Removing code from code behind in WPF

I'm trying to move some of the code behind in my project to a separate class. The part that I am interested in moving is the GetData method. I would like to move it out of my code behind to a separate class called DataAccess. I would appreciate your assistance. Thanks!

MainWindow.xaml.cs

namespace Contact_Interests
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private ObservableCollection<AggregatedLabel> myAggLabels;

    public ObservableCollection<AggregatedLabel> AggLabels
    {
        get { return myAggLabels; }
    }

    private ObservableCollection<ContactList> myContactLists;

    public IEnumerable<ContactList> ContactLists
    {
        get { return myContactLists; }
    }

    public MainWindow()
    {
        GetData();
        this.InitializeComponent();

        // Insert code required on object creation below this point.
    }

    public void GetData()
    {
        myAggLabels = new ObservableCollection<AggregatedLabel>();
        myContactLists = new ObservableCollection<ContactList>();

        DB2Connection conn = null;
        try
        {
            conn = new DB2Connection("XXXX;");
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message + " " + ex.InnerException);
        }

        //get all contactLists and their labels
        DB2Command command = new DB2Command("SQL SELECT statement");
        command.Connection = conn;

        conn.Open();

        //get all labels from database
        using (DB2DataReader dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
                AggregatedLabel aggLabel = new AggregatedLabel();

                aggLabel.ID = Convert.ToInt32(dr["LABEL_ID"]);
                aggLabel.Name = d开发者_StackOverflow社区r["LABEL_NAME"].ToString();

                myAggLabels.Add(aggLabel);

            }
        }
        //Add unique contactLists to dictionary
        Dictionary<int, ContactList> myContactDictionary = new Dictionary<int, ContactList>();

        using (DB2DataReader dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
               int id = Convert.ToInt32(dr["CONTACT_LIST_ID"]);

                if (!myContactDictionary.ContainsKey(id))
                {

                    ContactList contactList = new ContactList();

                    contactList.ContactListID = id;
                    contactList.ContactListName = dr["CONTACT_LIST_NAME"].ToString();
                    contactList.AggLabels = new ObservableCollection<AggregatedLabel>()
                {
                    new AggregatedLabel()
                    {
                        ID = Convert.ToInt32(dr["LABEL_ID"]),
                        Name = dr["LABEL_NAME"].ToString()
                    }

                };
                    myContactDictionary.Add(id, contactList);
                }
                else
                {
                    //populate existing contact lists with remaining labels
                    ContactList contactList = myContactDictionary[id];

                    contactList.AggLabels.Add
                    (
                        new AggregatedLabel() 
                        {
                            ID = Convert.ToInt32(dr["LABEL_ID"]),
                            Name = dr["LABEL_NAME"].ToString()
                        }
                    );
                }
            }
        }

        //add to observable collection      
        foreach (KeyValuePair<int, ContactList> contactKeyValue in myContactDictionary)
        {
            ContactList contactList = contactKeyValue.Value;

            myContactLists.Add(contactList);
        }

        conn.Close();        
    }
}


You should make a class for this, and just move all of your code into it.

Then create an instance of the class and set it as the DataContext for this Window.

If your interested in the mechanics, and the motivation (other than just pulling out of code behind), you can refer to my series on MVVM, or one of the many great MVVM introductions.


For example, your code above could be:

namespace Contact_Interests
{
    public partial class MainWindowViewModel // : INotifyPropertyChanged
    {
        private ObservableCollection<AggregatedLabel> myAggLabels;

        public ObservableCollection<AggregatedLabel> AggLabels
        {
            get { return myAggLabels; }
        }

        private ObservableCollection<ContactList> myContactLists;

        public IEnumerable<ContactList> ContactLists
        {
            get { return myContactLists; }
        }

        public MainWindowViewModel()
        {
            GetData();

            // Insert code required on object creation below this point.
        }

        public void GetData()
        {
            myAggLabels = new ObservableCollection<AggregatedLabel>();
            myContactLists = new ObservableCollection<ContactList>();

            DB2Connection conn = null;
            try
            {
                conn = new DB2Connection("XXXX;");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message + " " + ex.InnerException);
            }

            //get all contactLists and their labels
            DB2Command command = new DB2Command("SQL SELECT statement");
            command.Connection = conn;

            conn.Open();

            //get all labels from database
            using (DB2DataReader dr = command.ExecuteReader())
            {
                while (dr.Read())
                {
                    AggregatedLabel aggLabel = new AggregatedLabel();

                    aggLabel.ID = Convert.ToInt32(dr["LABEL_ID"]);
                    aggLabel.Name = dr["LABEL_NAME"].ToString();

                    myAggLabels.Add(aggLabel);

                }
            }
            //Add unique contactLists to dictionary
            Dictionary<int, ContactList> myContactDictionary = new Dictionary<int, ContactList>();

            using (DB2DataReader dr = command.ExecuteReader())
            {
                while (dr.Read())
                {
                   int id = Convert.ToInt32(dr["CONTACT_LIST_ID"]);

                    if (!myContactDictionary.ContainsKey(id))
                    {

                        ContactList contactList = new ContactList();

                        contactList.ContactListID = id;
                        contactList.ContactListName = dr["CONTACT_LIST_NAME"].ToString();
                        contactList.AggLabels = new ObservableCollection<AggregatedLabel>()
                    {
                        new AggregatedLabel()
                        {
                            ID = Convert.ToInt32(dr["LABEL_ID"]),
                            Name = dr["LABEL_NAME"].ToString()
                        }

                    };
                        myContactDictionary.Add(id, contactList);
                    }
                    else
                    {
                        //populate existing contact lists with remaining labels
                        ContactList contactList = myContactDictionary[id];

                        contactList.AggLabels.Add
                        (
                            new AggregatedLabel() 
                            {
                                ID = Convert.ToInt32(dr["LABEL_ID"]),
                                Name = dr["LABEL_NAME"].ToString()
                            }
                        );
                    }
                }
            }

            //add to observable collection      
            foreach (KeyValuePair<int, ContactList> contactKeyValue in myContactDictionary)
            {
                ContactList contactList = contactKeyValue.Value;

                myContactLists.Add(contactList);
            }

            conn.Close();        
        }
    }
}

Then, your main window becomes:

namespace Contact_Interests
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
         public MainWindow()
         {
              InitializeComponent();
              this.DataContext = new MainWindowViewModel();
         }
     }
 }


As Reed suggested, you should definitely look into the MVVM pattern if you're planning on working with WPF. The pattern is integral to how WPF works.

Heres an introduction to MVVM that really helped me understand the different aspects of the pattern.

http://blog.lab49.com/archives/2650
http://www.lab49.com/files/videos/Jason%20Dolinger%20MVVM.wmv

The video starts off with something similar to what you have, in that you have the processing code in the code-behind, Jason then proceeds to move code into separate classes and the end product is a clean separation of presentation and data processing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜