从WPF中的代码中删除代码

时间:2011-01-26 17:45:50

标签: c# wpf mvvm

我正在尝试将项目中的一些代码移到单独的类中。我感兴趣的部分是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();        
    }
}

2 个答案:

答案 0 :(得分:2)

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

然后创建该类的实例并将其设置为此窗口的DataContext

如果您对机制和动机感兴趣(除了背后的代码除外),您可以参考我的series on MVVM或其中一个很棒的MVVM introductions


例如,您的上述代码可能是:

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

答案 1 :(得分:1)

正如Reed建议的那样,如果你打算使用WPF,你一定要查看MVVM模式。该模式是WPF工作方式不可或缺的一部分。

下面介绍MVVM,它真正帮助我理解了模式的不同方面。

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

视频以类似于你所拥有的东西开始,因为你在代码隐藏中有处理代码,Jason然后继续将代码移动到单独的类中,最终产品是表示和数据处理的清晰分离