1

这不适合我:

<StackPanel>
    <ListBox x:Name="MyListBox"
        ItemsSource="{StaticResource UserControlsCollection}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
    <UserControl
        Content="{Binding ElementName=MyListBox, Path=SelectedValue}"
        />
</StackPanel>

我在运行时收到此“项目不在预期范围内”错误。这些是数据:

<toolkit:ObjectCollection x:Key="UserControlsCollection">
    <UserControl Style="{StaticResource UserControlListItemStyle}">
        <Button>One Button</Button>
    </UserControl>
    <UserControl Style="{StaticResource UserControlListItemStyle}">
        <ComboBox>
            <ComboBoxItem Content="One" IsSelected="True" />
            <ComboBoxItem Content="Two" />
            <ComboBoxItem Content="Three" />
        </ComboBox>
    </UserControl>
    <UserControl Style="{StaticResource UserControlListItemStyle}">
        <Rectangle
            Fill="Red"
            Width="120" Height="120"
            />
    </UserControl>
</toolkit:ObjectCollection>
4

1 回答 1

0

您试图显示相同的 FrameworkElements(集合中的那些)两次:一次作为 ListBox 中的项目,然后在绑定的 UserControl 中选择第二次。

所有 FrameworkElements 只能在可视化树中挂接一次(即当它们触发加载的事件时)。

要实现您想要做的事情,您需要分离模型和视图。模型将在您的集合中并且可以是任何类型,通常实现 INotifyPropertyChanged 或从 DependencyObject 派生,并且您的视图可以是 DataTemplates 作为资源,Target 属性是模型的类型。

从 SL5 开始,任何以模型作为其内容的 ContentControl(类似地,将模型作为绑定集合的元素的 ListBox)如果在范围内,则将自动拾取这些 DataTemplate。然后,模板可能会为每个模型实例化多次。

于 2012-06-07T11:18:23.863 回答