I'd like to "draw" several Polylines and some Textblocks or Labels in a Viewbox in WPF.

Since a Viewbox only allows a single Child, I tried to put the Polylines inside a Canvas Element which didn't work:

XAML:

<Viewbox Stretch="Uniform">
     <Canvas Margin="10">
        <Polyline 
                        Points="{Binding Path=Points2}"
                        Stroke="Green"
                        StrokeThickness="2" >
        </Polyline>
                    <!-- other Polylines, Textblocks etc.  would go here... -->
    </Canvas>
</Viewbox>

The Polyline is correctly drawn when I use this code (i.e. I simply dropped the Canvas):

<Viewbox Stretch="Uniform">
        <Polyline 
                        Points="{Binding Path=Points2}"
                        Stroke="Green"
                        StrokeThickness="2" >
        </Polyline>
</Viewbox>

I want to visualize some geometric properties like in a very minimalistic computer geometry program like geogebra for instance. Optionally some points should be movable in a next version, but this is not essential.

Solution:

<Viewbox Stretch="Uniform">
     <Grid>
        <Polyline 
                        Points="{Binding Path=Points2}"
                        Stroke="Green"
                        StrokeThickness="4" >
        </Polyline>
        <Polyline 
                        Points="{Binding Path=Points2}"
                        Stroke="Yellow"
                        StrokeThickness="2" >
        </Polyline>
    </Grid>
</Viewbox>

This puts to identical polygons on top of each other, i.e. thin yellow on top of wide green polyline.

The answer to this stackoverflow question helped me.

有帮助吗?

解决方案

The canvas doesn't really work for things like this, once you put your controls inside a canvas you ignore all layout. Can you instead put your poly lines inside a grid and use the margins to position them?

<Viewbox Stretch="Uniform">
    <Grid  Margin="10">
        <Polyline 
                    Points="{Binding Path=Points2}"
                    Stroke="Green"
                    StrokeThickness="2" >
        </Polyline>
    </Grid>
</Viewbox>

其他提示

The reason you can't see your Polylines is because the Canvas has a default Height and Width of 0.

Try setting the Height and Width explicitly.

<Viewbox x:Name="ViewBox" Stretch="Uniform">
    <Canvas x:Name="chartCanvas" Margin="10" Height="200" Width="300">
        <Polyline 
                Points="{Binding Path=Points2}"
                Stroke="Green"
                StrokeThickness="2">
        </Polyline>
        <!-- other Polylines, Textblocks etc.  would go here... -->
    </Canvas>
</Viewbox>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top