【问题标题】:Items collection must be empty before using ItemsSource在使用 ItemsSource 之前,项目集合必须为空
【发布时间】:2012-07-24 01:19:45
【问题描述】:

如果我将 DataTrigger 放在一个简单的列表框中,我会得到这个运行时异常:

Items 集合在使用 ItemsSource 之前必须为空

我的列表框没有数据触发器(也不例外):

<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>

后面的代码有什么问题?

【问题讨论】:

    标签: c# wpf xaml listbox datatrigger


    【解决方案1】:

    您没有正确声明样式,因此它被设置为列表框的 content - 您正在手动声明一个包含单个样式的列表。

    您应该用&lt;ListBox.Style&gt; 元素包装现有的Style 元素以解决此问题。

    【讨论】:

      【解决方案2】:

      您添加了Style 作为一个项目,您忘记了ListBox.Style 标签。由于您还尝试绑定ItemsSource,因此您会收到错误消息。

      【讨论】:

        猜你喜欢
        • 2010-10-15
        • 1970-01-01
        • 2012-03-04
        • 2013-08-08
        • 2012-08-02
        • 2014-01-07
        • 1970-01-01
        • 2010-12-08
        • 2023-03-11
        相关资源
        最近更新 更多