Wpf Items使用ViewModels控制用户控件
我想用XAML做一件非常简单的事情 我想在ItemControl中显示UserControl‘UserControl a’(带有viewModels‘ViewModel a’)的列表,托管在‘UserControl B’中 “ViewModel B”包含一个属性,该属性是“UserControls a”的可观察集合 在“userControls A”的Ctor中,我设置了:Wpf Items使用ViewModels控制用户控件,wpf,xaml,mvvm,user-controls,itemscontrol,Wpf,Xaml,Mvvm,User Controls,Itemscontrol,我想用XAML做一件非常简单的事情 我想在ItemControl中显示UserControl‘UserControl a’(带有viewModels‘ViewModel a’)的列表,托管在‘UserControl B’中 “ViewModel B”包含一个属性,该属性是“UserControls a”的可观察集合 在“userControls A”的Ctor中,我设置了: Me.DataContext = New ViewModelA() 在“userControlB”的Ctor中,我设置了
Me.DataContext = New ViewModelA()
在“userControlB”的Ctor中,我设置了相同的参数,但使用了“ViewModel B”
“ViewModel A”包含两个属性(整数)“行”和“列”
我想要的是绑定每个“userControl A”以及“userControl B”中托管的网格中的“Col”和“Row”的值
以下是我所做的:
用户控制B:
<ItemsControl ItemsSource="{Binding ListOfUserControl_A}" Margin="1.5">
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding Col}" />
<Setter Property="Grid.Row" Value="{Binding Row}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:UserControl_A/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在此过程之前,已正确填充集合
但在运行时,我有一个错误(翻译自法语):
集合必须为空才能使用“ItemsSource”
我之前遇到的另一个错误是“itemTemplate和ItemTemplateSelector对于UserControl_B无效”
我做错了什么 您忘记在
ItemsControl.ItemsPanel
标记中包装ItemsPanelTemplate
。如果没有ItemsControl
将ItemsPanelTemplate
视为一个项目,并且由于您已经设置了ItemsSource
,因此会出现该错误
<ItemsControl ItemsSource="{Binding ListOfUserControl_A}" Margin="1.5">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>