Items collection must be empty before using ItemsSource(在使用 ItemsSource 之前,项目集合必须为空)
问题描述
如果我将 DataTrigger 放在一个简单的列表框中,我会得到这个运行时异常:
If I put a DataTrigger in a simple Listbox I get this runtime exception:
Items 集合在使用 ItemsSource 之前必须为空
Items collection must be empty before using ItemsSource
我的列表框没有数据触发器(也不例外):
My listbox without datatrigger (no exception):
<ListBox ItemsSource="{Binding EdgedBoards}" SelectedItem="{Binding SelEdgedBoard, Mode=TwoWay}" DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}"
BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="IsSelected"
Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
我的列表框与 DataTrigger
:
<ListBox ItemsSource="{Binding EdgedBoards}" SelectedItem="{Binding SelEdgedBoard, Mode=TwoWay}" DisplayMemberPath="Name">
<Style TargetType="{x:Type ListBox}" BasedOn="{StaticResource {x:Type ListBox}}">
<Setter Property="Focusable" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EdgedBoardsAdd_UC, Path=Visibility}" Value="Visible">
<Setter Property="Focusable" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
后面的代码有什么问题?
What's wrong with the latter code?
推荐答案
你没有正确声明样式,所以它被设置为列表框的 content - 你手动声明了一个包含单个样式的列表.
You aren't declaring the style correctly, and so it's being set as the content of the listbox - you are manually declaring a list that contains a single style.
你应该用 <ListBox.Style>
元素包裹你现有的 Style
元素来解决这个问题.
You should wrap your existing Style
element with the <ListBox.Style>
element to fix this problem.
这篇关于在使用 ItemsSource 之前,项目集合必须为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在使用 ItemsSource 之前,项目集合必须为空


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01