“Items集合在使用ItemsSource之前必须为空”。 [英] "Items collection must be empty before using ItemsSource."

查看:1345
本文介绍了“Items集合在使用ItemsSource之前必须为空”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让图像显示在像旧版ATC Avalon Team文章中所描述的像WrapPanel一样的WPF ListView中:更高ItemsControl:

  [ContentPropertyAttribute(Items)] 
/ pre>

这里的意图是将ListView的视图设置为本地:ImageView,因此修正是明确指出要设置的属性。



修复XAML,异常消失:

 < ListView Name =ListViewImages 
SelectionMode =Single
ItemsSource ={Binding}>
< ListView.View>
< local:ImageView />
< /ListView.View>
< / ListView>

缺少< ListView.View> 标签。


I'm trying to get images to display in a WPF ListView styled like a WrapPanel as described in this old ATC Avalon Team article: How to Create a Custom View.

When I try to populate the ListView with a LINQ-to-Entities queried collection of ADO.NET Entity Framework objects I get the following exception:

Exception

Items collection must be empty before using ItemsSource.

My code…

Visual Basic

Private Sub Window1_Loaded(...) Handles MyBase.Loaded
    ListViewImages.ItemsSource = From g In db.Graphic _
                                 Order By g.DateAdded Ascending _
                                 Select g
End Sub

XAML

<ListView Name="ListViewImages"
          SelectionMode="Single"
          ItemsSource="{Binding}">
    <local:ImageView />
</ListView>

I put a breakpoint on that line. ListViewImages.ItemsSource is Nothing just before the LINQ assignment.

解决方案

The reason this particular exception gets thrown is that the content of the element gets applied to the ListView's Items collection. So the XAML initialises the ListView with a single local:ImageView in its Items collection. But when using an ItemsControl you must use either the Items property or the ItemsSource property, you can't use both at the same time. Hence when the ItemsSource attribute gets processed an exception is thrown.

You can find out which property the content of an element will get applied to by looking for the ContentPropertyAttribute on the class. In this case it's defined higher in the class hierarchy, on the ItemsControl:

[ContentPropertyAttribute("Items")]

The intention here was that the ListView's View be set to a local:ImageView so the fix is to explicitly indicate the property to be set.

Fix the XAML and the exception goes away:

<ListView Name="ListViewImages"
          SelectionMode="Single"
          ItemsSource="{Binding}">
    <ListView.View>
        <local:ImageView />
    </ListView.View>
</ListView>

It was missing that <ListView.View> tag.

这篇关于“Items集合在使用ItemsSource之前必须为空”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆