【发布时间】:2011-05-20 23:38:41
【问题描述】:
我有一个简单的例子,我正在创建一个由列表框组成的视图,列表框显示一堆项目。我想知道我是否要在这里正确地创建 View Model 和 Model 类。在这种情况下使用正确有效的任何值,我知道这有点主观,但我目前的解决方案感觉不对。这是一个简化版本。
ViewModel 和模型:
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>
在正确的代码中,列表框将使用数据模板来显示子视图模型。但是正如您所看到的,我不确定如何实例化与子相关的对象。感觉 ParentViewModel 会引用 ParentModel 并基于 ParentModel 的 ChildModel 对象创建 ChildViewModel 对象。现在我已经说过这听起来不那么愚蠢,但我会对你的想法感兴趣。
【问题讨论】: