Caliburn.Micro 将视图模型列表与 ItemsControl 绑定
本文关键字:ItemsControl 绑定 列表 模型 Micro 视图 Caliburn | 更新日期: 2023-09-27 18:31:23
我有一个视图模型,其中包含另一个视图模型的集合。 我想使用视图模型的集合作为ItemsControl
的ItemsSource
来显示相应的视图。 我收到此错误: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
}
与集合中使用的视图模型对应的视图
<UserControl x:Class="Fallout4Checklist.Views.Partial.WeaponDetail"
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:local="clr-namespace:Fallout4Checklist.Views.Partial">
<StackPanel>
<Border Style="{StaticResource WeaponDetailNameBorder}">
<Label Style="{StaticResource WeaponDetailName}" />
</Border>
<StackPanel Style="{StaticResource WeaponDetailContainer}">
<Border Style="{StaticResource ImageBorder}">
<Image Source="{Binding ImagePath.FullPath}" />
</Border>
<Border Style="{StaticResource ItemDescriptionBorder}">
<TextBlock Style="{StaticResource ItemDescription}" Text="{Binding Characteristics}" />
</Border>
</StackPanel>
</StackPanel>
</UserControl>
首先,您应该阅读有关 codeplex 的文档 (https://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Conventions)。
但是,我认为您的itemcontrol的内部元素声明是错误的。
换句话说,删除
<ContentControl cal:View.Model="{Binding /}" />
并为项目控件中的项目创建项目模板
<DataTemplate>
<ContentControl cal:View.Model="{Binding}" />
</DataTemplate>