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?
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With