WPF 自定义形状 [英] WPF Custom shape

查看:42
本文介绍了WPF 自定义形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个自定义形状以添加到 WPF 表单中.形状只是一个三角形.如果您想知道,是的,我可以使用 XAML 中的多边形来做到这一点:

I need to create a custom shape to add on a WPF form. The shape is just a triangle. If you are wondering, yes, I can do that with a Polygon in XAML with this:

<Polygon Fill="LightBlue" Stroke="Black" Name="Triangle">
  <Polygon.Points>
    <Point X="0" Y="0"></Point>
    <Point X="10" Y="0"></Point>
    <Point X="5" Y="-10"></Point>
  </Polygon.Points>
</Polygon>

问题是我们需要从其他地方绑定一个最终决定形状大小的属性.所以,我写了一个形状类的简单扩展,如下所示:

The problem is that we need to bind a property from somewhere else that ultimately determines the size of the shape. So, I wrote a simple extension of the shape class like this:

public class Triangle:Shape
{
    private double size;

    public static readonly DependencyProperty SizeProperty = DependencyProperty.Register("Size", typeof(Double), typeof(Triangle));

    public Triangle() {            
    }

    public double Size
    {
        get { return size; }
        set { size = value; }
    }

    protected override Geometry DefiningGeometry
    {
        get {

            Point p1 = new Point(0.0d,0.0d);
            Point p2 = new Point(this.Size, 0.0d);
            Point p3 = new Point(this.Size / 2, -this.Size);

            List<PathSegment> segments = new List<PathSegment>(3);
            segments.Add(new LineSegment(p1,true));
            segments.Add(new LineSegment(p2, true));
            segments.Add(new LineSegment(p3, true));

            List<PathFigure> figures = new List<PathFigure>(1);
            PathFigure pf = new PathFigure(p1, segments, true);
            figures.Add(pf);

            Geometry g = new PathGeometry(figures, FillRule.EvenOdd, null);

            return g;
        }
    }

}

我认为这很好,但形状没有出现在表格的任何地方.所以,我不确定 DefiningGeometry 方法是否写得很好.如果我看不到任何东西,很可能不是.谢谢!

I thought that was good but the shape does not show up anywhere on the form. So, I am not sure if the DefiningGeometry method is well written. And if I cannot see anything very likely is not. Thanks!

推荐答案

依赖属性设置不正确.像这样编写Size getter/setter:

The dependency property isn't set up correctly. Write the Size getter/setter like this:

public double Size
{
    get { return (double)this.GetValue(SizeProperty); }
    set { this.SetValue(SizeProperty, value); }
}

这篇关于WPF 自定义形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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