我有一个简单的示例,其中创建了一个视图,包含一个列表框,该列表框显示了许多项目。我想知道在这里创建View Model和Model类的方法是否正确。在此上下文中使用“正确”的任何值都可以,我知道这有点主观,但我当前的解决方案感觉不对。以下是一个简化版本。
ViewModels 和 Models:
namespace Example
{
public class ParentViewModel
{
public ParentViewModel()
{
// ... Create/Consume ChildViewModel * n
}
public List<ChildViewModel> ChildViewModels { get; set; }
}
public class ChildViewModel
{
public ChildViewModel()
{
// ... Create/Consume ChildModel
}
public ChildModel Model { get; set; }
}
public class ParentModel
{
public List<ChildModel> ChildModels { get; set; }
public ParentModel()
{
// ... Create/Consume ChildModel * n;
}
}
public class ChildModel
{
public ChildModel()
{
// ... Contains actual data.
}
public string Data { get; set; }
}
}
视图:
<Window x:Class="Example.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Example="clr-namespace:Example" Title="View" Height="300" Width="300"
DataContext="{StaticResource TheViewModel}">
<Window.Resources>
<Example:ParentViewModel x:Key="TheViewModel" />
</Window.Resources>
<Grid>
<ListBox Height="261" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="278" ItemsSource="{Binding ChildViewModels}"/>
</Grid>
在正确的代码中,列表框将使用数据模板来显示子视图模型。但正如您所看到的,我不确定如何实例化与子相关的对象。感觉父视图模型将引用父模型并根据父模型的子模型对象创建ChildViewModel对象。现在我已经这么说了,听起来不那么愚蠢,但我很想听听您的想法。