How to set object who pass to template, as binding

2019-03-01 16:21发布

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条回答
地球回转人心会变
2楼-- · 2019-03-01 16:47

Here is an example which uses a ListBox to hold the points collections.

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

Now it is simply a matter of loading up the AllPoints list

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)}),
};

When run I get this output

enter image description here


Update

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

Here is using a composite collection

public CompositeCollection MyCompositeCollection ...

Here are all the data templates

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

And the result showing three different objects:

enter image description here


See my answer using an ObserableCollection<T> (where the ship and passage both had the same interface) here on SO How to format a string in XAML without changing viewmodel's property getter?.

查看更多
登录 后发表回答