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

同じ FrameworkElement (コレクション内のもの) を 2 回表示しようとしています。

すべての FrameworkElements は、ビジュアル ツリーで 1 回だけフックできます (つまり、読み込まれたイベントが発生したとき)。

やろうとしていることを達成するには、モデルとビューを分離する必要があります。モデルはコレクション内にあり、通常は INotifyPropertyChanged を実装するか、DependencyObject から派生する任意の型にすることができます。ビューは、モデルの型である Target 属性を持つリソースとして DataTemplates にすることができます。

SL5 以降、コンテンツとしてモデルを持つ ContentControl (バインドされたコレクションの要素としてモデルを持つ ListBox と同様) は、スコープ内にある場合、それらの DataTemplates を自動的に取得します。テンプレートは、モデルごとに複数回インスタンス化される可能性があります。

于 2012-06-07T11:18:23.863 に答える