Items collection must be empty before using ItemsSource

[亡魂溺海] 提交于 2019-12-20 03:55:23

问题


If I put a DataTrigger in a simple Listbox I get this runtime exception:

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>

My ListBox with 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?


回答1:


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.

You should wrap your existing Style element with the <ListBox.Style> element to fix this problem.




回答2:


You added the Style as an item, you forgot the ListBox.Style tags. Since you also try to bind the ItemsSource you get the error.



来源:https://stackoverflow.com/questions/11652623/items-collection-must-be-empty-before-using-itemssource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!