0

次のように ItemsControl を設定しています。

<Grid>
    <ItemsControl ItemsSource="{Binding Asteroids}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas Background="Black">
                        <!-- i want to add another polygon to the canvas-->
                        <!--<Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />-->
                    </Canvas>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>

ご覧のとおり、ItemsControl はコレクションの要素を Canvas 内の Polygon として表示しています。しかし、ここでは「ShipPolygon」という名前の別のポリゴンをこのキャンバスに追加したいと考えています。XMLParseException が発生するため、この方法では実行できません。これを行う適切な方法は何ですか?前もって感謝します!

4

1 に答える 1

4

アイテムパネルに複数の同様のアイテムを表示するためにある ItemsControl を使用しています。

明らかに、そこに何かを追加することはできませんItemsPanelTemplate。アイテムを表示するためにどのパネルを使用する必要があるかを itemscontrol に伝えるだけです。ItemsSource と ItemTemplate は、ItemsControl に小惑星のみを表示したいことを示唆しています。したがって、最も簡単な方法は、船を小惑星でアイテムコントロールにオーバーレイすることです

<Grid>
    <ItemsControl ItemsSource="{Binding Asteroids}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas Background="Black"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
    </ItemsControl>

    <Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />
</Grid>

それ以外の場合は、アイテム コントロールにも追加できますが、別の ItemTemplates を使用する必要があります。そして、ItemsControl が小惑星のみを保持しなくなったことを処理する必要があります。暗黙的なアイテム テンプレートの使用

<!-- No key, so it is implicit and automatically used-->
<DataTemplate DataType="{x:Type Asteroids}">
    <Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
</DataTemplate>

<DataTemplate DataType="{x:Type Player}">
    <Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />
</DataTemplate>

<!-- above must be in a resource section, like app.xaml -->


<Grid>
    <ItemsControl ItemsSource="{Binding Entities}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas Background="Black"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>

または、DataTemplateSelector を使用できます。

于 2012-05-29T09:00:36.247 に答える