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

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

问题描述

我正在尝试让图像显示在 WPF ListView 中,样式类似于 ATC Avalon Team 这篇旧文章中所述:在ItemsControl 上的类层次结构:

[ContentPropertyAttribute(项目")]

这里的目的是将 ListView 的 View 设置为 local:ImageView,因此修复是明确指示要设置的属性.

修复 XAML,异常消失:

<ListView.View><local:ImageView/></ListView.View></ListView>

缺少 标签.

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.

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

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