我遇到麻煩,將項目添加到ObservableCollection時使用ItemsSource列表框。我在我的viewmodels構造函數中添加了用於測試的虛擬數據。MVVM WPF ObservableCollection:錯誤addign項目,ItemsSource綁定
我的視圖模型:
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了吧。」}。謝謝你的幫助!
你的應用程序中是否有任何其他代碼試圖直接向/從ListBox添加/刪除項目,而不是使用KabaDevices屬性? –