我有一个包含另一个视图模型集合的视图模型。我想将视图模型集合用作ItemsSource
的{{1}}来显示相应的视图。我收到此错误:ItemsControl
。每次items collection must be empty before using itemssource
更改时,我都想创建新的视图模型。
父视图模型
CurrentArea
家长视图
public class AreaDetailViewModel : Screen
{
public AreaDetailViewModel()
{
CurrentAreaWeapons = new ObservableCollection<WeaponDetailViewModel>();
DisplayName = "Area Details";
using (var repo = new AreaDetailRepository())
Areas = repo.GetAreas();
}
public List<Area> Areas;
public Area CurrentArea
{
get { return _currentArea; }
set
{
_currentArea = value;
DisplayName = _currentArea.Name;
NotifyOfPropertyChange(() => CurrentArea);
SetWeaponDetailViewModels();
}
}
private Area _currentArea;
private void SetWeaponDetailViewModels()
{
CurrentAreaWeapons.Clear();
foreach (var item in _currentArea.Weapons)
CurrentAreaWeapons.Add(new WeaponDetailViewModel(item));
}
}
查看集合中使用的模型
<UserControl x:Class="Fallout4Checklist.Views.AreaDetailView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cal="http://www.caliburnproject.org">
<ScrollViewer>
<StackPanel>
<Border Style="{StaticResource WeaponContainer}">
<StackPanel>
<Label Style="{StaticResource WeaponHeader}" />
<ItemsControl ItemsSource="{Binding CurrentAreaWeapons}">
<ContentControl cal:View.Model="{Binding /}" />
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
查看对应于查看集合中使用的模型
public class WeaponDetailViewModel : PropertyChangedBase
{
// NOTHING SPECIAL HERE
}
答案 0 :(得分:4)
首先,您应阅读有关codeplex(https://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Conventions)的文档。
然而,我相信你的itemcontrol的内部元素声明是错误的。
换句话说,删除
<ContentControl cal:View.Model="{Binding /}" />
为ItemsControl中的项目创建一个itemstemplate
<DataTemplate>
<ContentControl cal:View.Model="{Binding}" />
</DataTemplate>