0

在使用带有 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 访问和修改元素。”}。谢谢你的帮助!

4

1 回答 1

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;
}
于 2013-10-02T06:15:09.773 回答