gpt4 book ai didi

c# - 使用集合时如何在MVVM中同步数据

转载 作者:行者123 更新时间:2023-12-03 10:44:50 25 4
gpt4 key购买 nike

最近,我开始研究MVVM,以构建我正在处理的WPF应用程序。我正在努力了解如何使模型和ViewModel之间的集合保持同步,以及与此相关的如何验证用户将输入的信息。

假设我有一个(理论上的)建筑类,即模型,它将在运行时在内存中存储建筑布局,否则将通过序列化存储在xml中。建筑物具有一个成员列表,并且该列表中的每个条目楼层可以具有其他列表,例如列表和列表,它们又可以具有成员(即列表)。

该模型:

namespace TestMVVM
{
public class Building
{
public string strName { get; set; }
public List<Floor> floors { get; set; }
}

public class Floor
{
public int iNumber { get; set; }
public List<Room> rooms { get; set; }
}

public class Room
{
public int iSize { get; set; }
public string strName { get; set; }
public List<Door> doors { get; set; }
}

public class Door
{
public bool bIsLocked { get; set; }
}
}

在 View 中,Floor类型的列表将在DataGrid中可编辑。用户可以在DataGrid中输入新行,以将Floor添加到Building类。在另一个DataGrid中,可以将房间添加到楼层。当我将所有列表都放入ObservableCollections并将它们直接与View耦合时,这非常容易。但是,这也意味着没有适当的关注点分离,一旦验证生效,它就会变得困惑。

所以我写了一个ViewModel类,BuildingViewModel。它将保留对模型实例的引用。这是我遇到麻烦的地方:ViewModel将保存一个类型为FloorViewModel的ObservableCollection。但是,当用户添加条目时,如何将条目也添加到模型的列表中?大多数情况下,保持数据同步?如果将房间添加到地板或房间的门,该如何知道在模型中的何处更新哪些数据呢? IE。如何同步嵌套列表成员数据?

随后,我将确保不会创建重复的楼层。 IE。如果用户使用列表中已有的数字添加楼层,则DataGrid必须报告错误。如果编辑现有楼层,则相同;对于“房间名称”,则相同。我认为在FloorViewModel类中无法进行这种错误检查,因为它无法访问其自身的其他实例。

我进行了很多搜索,但没有找到明确的答案。这看起来是很普通的情况吗?也许我只是在朝着错误的方向前进?

这是当前的ViewModel,其中ViewModelBase是通用类,包含INotifyProretyChanged和INotifyDataErrorInfo的实现。
namespace TestMVVM
{
public class BuildingViewModel : ViewModelBase
{
private Building building;

public string strName
{
get { return building.strName; }
set
{
building.strName = value;
if (value == "") AddError("strName", "Name cannot be empty.");
OnPropertyChanged("strName");
}
}

public ObservableCollection<FloorViewModel> floors
{
// what goes here? how to sync members of floor to the model, and validate data?
}

public BuildingViewModel(Building b)
{
building = b;
}
}

public class FloorViewModel : ViewModelBase
{
public ObservableCollection<Room> rooms
{
// what goes here? how to sync members of room to the right Floor of the model, and validate data?
}
}

// etc
}

最佳答案

您提供的类中存在问题。尝试应用Demeter定律,观看this video关于如何正确构造House对象(甚至是相同的示例),然后您仅调用正确级别的addX()方法即可进行验证。

关于c# - 使用集合时如何在MVVM中同步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com