在画布WPF元素定位 [英] WPF element positioning on a Canvas

查看:293
本文介绍了在画布WPF元素定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要放置一个椭圆在画布上的一个点。我想要的椭圆的中心将超过这一点。目前左上角的椭圆的最边缘了这一点。

I have a point on a canvas that I want to place an ellipse. I want the centre of the ellipse to be over this point. At the moment the top left most edge of the ellipse is over this point.

我知道我可以在画布上编程移椭圆形,但我不知道是否有一种方法来告诉WPF居中从左上角???

I know I can shift the ellipse programmatically on the canvas but I was wondering if there is a way to tell WPF to centre the element over the point instead of sizing it from the top left???

推荐答案

我不知道任何内置的功能,在椭圆设置其上的一个点中心,但你可以扩展椭圆类来做到这一点。

I do not know of any in built in feature in Ellipse to set its center on a point, but you can extend the Ellipse class to do it.

添加此类项目

public static class EllipseX 
{
    public static void SetCenter(this Ellipse ellipse, double X, double Y)
    {
        Canvas.SetTop(ellipse, Y - ellipse.Height/2);
        Canvas.SetLeft(ellipse, X - ellipse.Width/2);
    }
}

然后在XAML创建椭圆

Then in xaml create the Ellipse

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
   <Canvas Background="LightGray">
      <Ellipse      
          Name="myEllipse"      
          Fill="Red"
          Height="75"
          Width="75"
       />
   </Canvas>
</Window>

然后写int后code $ c中$ C背后:

Then write int following code in code behind:

myEllipse.SetCenter(200,200);

这样做的好处是,你不必再重复找到中心,你创建的每一个椭圆的逻辑。

The advantage of this is that you do not have to repeat the logic of finding center in every ellipse you create.

希望这有助于。

这篇关于在画布WPF元素定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆