Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Center Ellipse at X, Y

Tags:

wpf

I have an ItemsControl that draws thousands of Ellipses in a scatter plot on a Canvas. My problem is, if I position an Ellipse at the coordinates (4, 6) with a Height and Width of 10. The top left of the Ellipse is at (4, 6) and the shape extends down and to the right.

What I'd like to do is center the Ellipses on specific coordinates in XAML without having to use adjustments in my ViewModel layer.

Here's the working UserControl that has my graph:

<Grid>
        <ItemsControl ItemsSource="{Binding State.Data}">

            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas  ClipToBounds="False"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>

            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Canvas.Left" Value="{Binding Path=X}" />
                    <Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
                </Style>
            </ItemsControl.ItemContainerStyle>

            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Ellipse Fill="Red"  VerticalAlignment="Center" HorizontalAlignment="Center"  Width="10" Height="20"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>

        </ItemsControl>
    </Grid>

This works great except for the uncentered ellipses. Any ideas?

like image 431
bufferz Avatar asked Mar 24 '11 17:03

bufferz


3 Answers

You can use EllipseGeometry to accomplish this.

The XAML:

<Path Stroke="Black" StrokeThickness="3" Fill="Red" >
    <Path.Data>
        <EllipseGeometry 
            Center="{Binding Path=CenterPoint}" 
            RadiusX="5" 
            RadiusY="10" />
    </Path.Data>
</Path>

The View Model:

public Point CenterPoint { get; set;}

Can't take credit, I found this here.

like image 91
Robert Gowland Avatar answered Nov 10 '22 00:11

Robert Gowland


Its not fully automatic but this solution does at least keep the centering logic inside the view and doesn't muddy your model

<Ellipse Fill="Red" Width="10" Height="20">
  <Ellipse.RenderTransform>
    <TranslateTransform X="-5" Y="-10" />
   </Ellipse.RenderTransform>
</Ellipse>
like image 29
Mr Bell Avatar answered Nov 09 '22 23:11

Mr Bell


I suggest, you DO change your ViewModel and name the properties Left and Top, so it is clear what is meant. If you also need the X and Y values, just leave them. I suggest this, because X and Y can mean different things, dependent on the shape you are drawing.

like image 24
Daniel Hilgarth Avatar answered Nov 10 '22 00:11

Daniel Hilgarth