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

Edu*_*tes 1 c# wpf xaml listbox datatrigger

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

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

我没有datatrigger的列表框(没有例外):

<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>
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

后一个代码有什么问题?

Dan*_*zey 7

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

您应该Style使用<ListBox.Style>元素包装现有元素以解决此问题.