Wpf 如何将传递给模板的对象设置为绑定?

Wpf 如何将传递给模板的对象设置为绑定?,wpf,wpf-controls,Wpf,Wpf Controls,我有一个数据模板: <DataTemplate DataType="{x:Type PointCollection}"> <Polygon Stroke="Blue" Points="{Binding}"Fill="White"/> </DataTemplate> 我需要把点集合放在多边形的点属性中。这是什么语法 我使用CompositeCollection作为ItemsSource,它包含不同类型的对象,因此,我不能只绑定模型的某些属性。下面

我有一个数据模板:

 <DataTemplate DataType="{x:Type PointCollection}">
   <Polygon Stroke="Blue" Points="{Binding}"Fill="White"/>
 </DataTemplate>

我需要把点集合放在多边形的点属性中。这是什么语法


我使用CompositeCollection作为ItemsSource,它包含不同类型的对象,因此,我不能只绑定模型的某些属性。

下面是一个使用列表框保存点集合的示例

<Grid>
    <Grid.Resources>
       <DataTemplate DataType="{x:Type PointCollection}">
          <StackPanel Orientation="Horizontal">
             <TextBlock Text="{Binding Count, StringFormat=Points: {0} }"
                        Margin="0,0,6,0" />
             <Polygon Stroke="Blue"
                      Points="{Binding}"
                      Fill="White" />
          </StackPanel>
       </DataTemplate>
    </Grid.Resources>

    <ListBox  HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              ItemsSource="{Binding AllPoints}"/>
</Grid>
以下是所有的数据模板

<DataTemplate DataType="{x:Type c:Ship}">
    <TextBlock Text="{Binding Path=Name, StringFormat=Ship: {0}}"
               Foreground="Red" />
</DataTemplate>
<DataTemplate DataType="{x:Type c:Passage}">
    <TextBlock Text="{Binding Path=Name, StringFormat=Passage: {0}}"
               Foreground="Blue" />
</DataTemplate>
<DataTemplate DataType="{x:Type PointCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Count, StringFormat=Points: {0} }"
                    Margin="0,0,6,0" />
        <Polygon Stroke="Blue"
                    Points="{Binding}"
                    Fill="White" />
    </StackPanel>
</DataTemplate>


<ListBox ItemsSource="{Binding MyCompositeCollection}"   />

结果显示了三个不同的对象:



查看我的答案,在这里使用
ObserableCollection
(其中船舶和通道都有相同的接口)如此。

可能重复Nope,在该问题中,PointCollection不绑定到datatemplate。它是否在datatemplate中并不重要,绑定将以相同的方式工作。您可能需要根据每个项的DataContext是什么来更改绑定路径。也许是这样的:。。。。
public CompositeCollection MyCompositeCollection ...
<DataTemplate DataType="{x:Type c:Ship}">
    <TextBlock Text="{Binding Path=Name, StringFormat=Ship: {0}}"
               Foreground="Red" />
</DataTemplate>
<DataTemplate DataType="{x:Type c:Passage}">
    <TextBlock Text="{Binding Path=Name, StringFormat=Passage: {0}}"
               Foreground="Blue" />
</DataTemplate>
<DataTemplate DataType="{x:Type PointCollection}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Count, StringFormat=Points: {0} }"
                    Margin="0,0,6,0" />
        <Polygon Stroke="Blue"
                    Points="{Binding}"
                    Fill="White" />
    </StackPanel>
</DataTemplate>


<ListBox ItemsSource="{Binding MyCompositeCollection}"   />