我有一个简单的示例,其中我正在创建一个由列表框组成的视图,并且该列表框显示一堆项目。我想知道我是否在这里正确创建视图模型和模型类。在这种情况下使用正确的任何值,我知道这有点主观,但我当前的解决方案感觉不正确。这是一个简化版本。
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 对象。现在我已经说过,这听起来并不那么愚蠢,但我对你的想法很感兴趣。
你走在正确的轨道上。
父模型自然会包含子模型列表,例如有多个订单的客户。
When ParentViewModel
由第三方创建并加载,它传递一个ParentModel
。然后ParentViewModel
will:
- 分配
ParentModel
到局部变量
- 创建一个
ChildViewModel
对于每个ChildModel
通过通过ChildModel
to the ChildViewModel
构造函数
- 添加每一个
ChildViewModels
到一个列表
顺便说一句,你想要
public List<ChildViewModel> ChildViewModels { get; set; }
to be
public ObservableCollection<ChildViewModel> ChildViewModels { get; set; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)