MVVM WPF ObservableCollection:错误添加项目,ItemsSource绑定

时间:2013-10-02 05:46:50

标签: wpf xaml mvvm listbox itemssource

在使用带有ItemsSource的列表框时,我在向ObservableCollection添加项目时遇到了麻烦。我在viewmodels构造函数中添加了用于测试的虚拟数据。

我的观点模型:

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是:{&#34;当ItemsSource正在使用时,操作无效。使用ItemsControl.ItemsSource访问和修改元素。&#34;}。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您的构造函数中可能存在问题。您将支持字段_details分配给该支持字段KabaDevices的公共属性。不是100%肯定这是否是异常的原因,但据我所知,其他一切都应该正常工作。试试这个:

public KabaDeviceListViewModel()
{

    var 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;
}