简体   繁体   中英

Creating new Classes / File Management in WPF Application

I'm new to WPF Application development.

For my current project I've been writing all of my code in MainWindow.xaml.cs, but it's getting very long (370 lines currently).

My guess is that the best way to separate code is to create separate classes, create instances of said class in MainWindow.xaml.cs and access their functions from there.

Here's an example:

namespace Outrun.Source
{
    public class Saver : MainWindow
    {
        public void SaveTaskList()
        {
            //Put all tasks in a list of strings.
            List<string> tasks = new List<string>();

            for (int i = 0; i < taskListBox.Items.Count; i++)
            {
                tasks.Add(taskListBox.Items[i].ToString());
            }

            //Write all tasks to a .txt file.
            string path = AppDomain.CurrentDomain.BaseDirectory + "OutrunSaveFile.txt";

            for (int i = 0; i < tasks.Count; i++)
            {
                File.WriteAllLines(path, tasks);
            }
        }
    }
}

The issue I have is getting access to functions and classes that I use in MainWindow.xaml.cs. Currently I have access to the ListBox element in my SaveTaskList() function because I inherit from MainWindow.

Is this the correct way to separate c# code? If not, what is the best way to separate c# code so my MainWindow.xaml.cs doesn't get wwwaaayyyy too long?

The best way for WPF application is to use MVVM pattern. There are a lots of tutorials around, so you should look at that.

With this pattern your ViewModels contain data and commands necessary for interaction and presentation, Views are (most of the time) just a pure XAML and you connect them using databinding. In this case, you don't need an access to the ListBox elements, just put the data in the ObservableCollection and let the databinding does its work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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