如果我将 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 之前,项目集合必须为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!