首页 > 解决方案 > 在 WPF 应用程序中创建新的类/文件管理

问题描述

我是 WPF 应用程序开发的新手。

对于我当前的项目,我一直在 MainWindow.xaml.cs 中编写我的所有代码,但它变得很长(目前 370 行)。

我的猜测是分离代码的最佳方法是创建单独的类,在 MainWindow.xaml.cs 中创建所述类的实例并从那里访问它们的函数。

这是一个例子:

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

我遇到的问题是访问我在 MainWindow.xaml.cs 中使用的函数和类。目前我可以访问我的 SaveTaskList() 函数中的 ListBox 元素,因为我继承自 MainWindow。

这是分离 c# 代码的正确方法吗?如果不是,那么分离 c# 代码的最佳方法是什么,以便我的 MainWindow.xaml.cs 不会太长 wwwaaayyyy?

标签: c#wpfxaml

解决方案


WPF 应用程序的最佳方式是使用 MVVM 模式。周围有很多教程,所以你应该看看。

使用这种模式,您的 ViewModel 包含交互和演示所需的数据和命令,视图(大多数情况下)只是一个纯 XAML,您可以使用数据绑定将它们连接起来。在这种情况下,您不需要访问 ListBox 元素,只需将数据放入 ObservableCollection 并让数据绑定完成其工作。


推荐阅读