繁体   English   中英

在WPF中从后面的代码中删除代码

[英]Removing code from code behind in WPF

我正在尝试将项目中的某些代码移到单独的类中。 我感兴趣的部分是GetData方法。 我想将其从代码中移到另一个名为DataAccess的类中。 多谢您的协助。 谢谢!

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 = 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();        
    }
}

您应该为此创建一个类,然后将所有代码移入其中。

然后创建该类的实例,并将其设置为该Window的DataContext

如果您对机制和动机感兴趣(而不仅仅是退出背后的代码),则可以参考我关于MVVM的系列文章 ,或者是许多很棒的MVVM简介之一


例如,上面的代码可能是:

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();        
        }
    }
}

然后,您的主窗口变为:

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

正如Reed所建议的,如果您打算使用WPF,则一定要研究MVVM模式。 该模式是WPF工作方式不可或缺的一部分。

这是MVVM的简介,它确实帮助我了解了模式的不同方面。

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

该视频的开头与您所拥有的类似,因为您在代码的后面有处理代码,Jason随后将代码移到单独的类中,最终产品将表示和数据处理完全分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM