在使用带有 ItemsSource 的列表框时,我在将项目添加到 ObservableCollection 时遇到了麻烦。我在我的视图模型构造函数中添加了用于测试的虚拟数据。
我的视图模型:
public class KabaDeviceListViewModel : KabaBase
{
private ObservableCollection<KabaDeviceDetailViewModel> _details;
public ObservableCollection<KabaDeviceDetailViewModel> KabaDevices
{
get { return _details; }
set
{
if (value != _details)
{
_details = value;
OnPropertyChanged("KabaDevices");
}
}
}
public KabaDeviceListViewModel()
{
ObservableCollection<KabaDeviceDetailViewModel> _details = new ObservableCollection<KabaDeviceDetailViewModel>();
KabaDevice kd1 = new KabaDevice("localhost A", "127.0.0.1", true);
KabaDeviceDetailViewModel dvm = new KabaDeviceDetailViewModel(kd1);
_details.Add(dvm);
KabaDevice kd2 = new KabaDevice("localhost B", "127.0.0.1", true);
KabaDeviceDetailViewModel dvm2 = new KabaDeviceDetailViewModel(kd2);
_details.Add(dvm2);
this.KabaDevices = _details;
}
}
到目前为止一切顺利,但在 XAML 代码中出现错误,在列表框的 ItemsSource 上。我看不出我做错了什么。我使用 VS2010 和 .NET 4.0。
<UserControl x:Class="KabaTest.View.KabaDeviceListView"
...
xmlns:myViewModels="clr-namespace:KabaTest.ViewModel"
xmlns:myViews="clr-namespace:KabaTest.View">
<UserControl.DataContext>
<myViewModels:KabaDeviceListViewModel/>
</UserControl.DataContext>
<Grid>
<ListBox Margin="5"
ItemsSource="{Binding Path=KabaDevices, Mode=TwoWay}" >
ScrollViewer.HorizontalScrollBarVisibility="Disabled" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type myViewModels:KabaDeviceDetailViewModel}" >
<myViews:KabaDeviceDetailView DataContext="{Binding }"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
ItemsSource 的 InnerException 是:{“使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素。”}。谢谢你的帮助!