How to set object who pass to template, as binding?

时间:2015-07-28 17:02:48

标签: wpf wpf-controls

I have DataTemplate:

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

and I need to put PointCollection in Points property of Polygon. What syntax for this?

I use CompositeCollection as ItemsSource, which contains objects of different types, so, I can't just bind some property of my Model.

1 个答案:

答案 0 :(得分:1)

这是一个使用ListBox来保存点集合的示例。

<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>

现在只需加载AllPoints列表

AllPoints = new List<PointCollection>()
{
    new PointCollection(new[] {new Point(1, 2), new Point(34, 12), new Point(12, 99)}),
    new PointCollection(new[] {new Point(9, 9), new Point(8, 8)}),
};

运行时我得到此输出

enter image description here

<强>更新

  

我使用CompositeCollection作为ItemsSource,其中包含对象   不同的类型,所以,我不能只绑定我的模型的一些属性。

这是使用复合集合

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}"   />

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

enter image description here

使用ObserableCollection<T>(船舶和通道都具有相同的界面)在SO How to format a string in XAML without changing viewmodel's property getter?上查看我的回答。