c# - 在 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?
解决方案
WPF 应用程序的最佳方式是使用 MVVM 模式。周围有很多教程,所以你应该看看。
使用这种模式,您的 ViewModel 包含交互和演示所需的数据和命令,视图(大多数情况下)只是一个纯 XAML,您可以使用数据绑定将它们连接起来。在这种情况下,您不需要访问 ListBox 元素,只需将数据放入 ObservableCollection 并让数据绑定完成其工作。
推荐阅读
- javascript - 使用 java-script 在 iOS Safari 上显示 base64 PDF
- python - 使用回溯的图形着色的平均复杂度
- html - README.md 同行对齐
- mongodb - 在单个字段上返回带有条件的查找结果
- google-cloud-pubsub - 关于 GCP PubSub Push 订阅者验证 jwt
- amp-html - AMPHTML - 打印适合打印的页面
- azure - Azure 管道 - 在功能分支上触发
- python-3.x - 如何紧固Knn算法进行实时人脸识别
- database - dolphindb中如何配置每个数据节点的参数?
- javascript - 如果对象属性值符合某些条件,如何在反应中呈现数据?