如何正确刷新WPF中的自定义形状? [英] How to properly refresh a custom shape in WPF?

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

问题描述

我创建了一个自定义行,旁边有一些文本。该形状是 System.Windows.Shapes.Shape 的子类。由于某些原因,当我更改直线的坐标时,文本不会刷新。我知道 InvalidateVisual()方法,但是每次我移动元素时,都必须调用它以重绘形状。我敢肯定有更好的方法。我究竟做错了什么?

I created a custom line with some text next to it. The shape is a subclass of System.Windows.Shapes.Shape. For some reason the text does not refresh when I change the coordinates for the line. I know about the InvalidateVisual() approach, but then every time I move elements around I would have to call it to redraw the shape. I am sure there is a better way of doing it. What am I doing wrong? ATM I am out of ideas.

public class MyShape : Shape
{
    LineGeometry line;
    FormattedText text;

    public MyShape()
    {
        line = new LineGeometry();
        text = new FormattedText(
                Edge.Length.ToString(),
                Thread.CurrentThread.CurrentCulture,
                System.Windows.FlowDirection.LeftToRight,
                new Typeface("Verdana"), 10, Brushes.Black);
    }

    // Specify the X1 dependency property:
    public static readonly DependencyProperty X1Property =
        DependencyProperty.Register("X1",
        typeof(double), typeof(MyShape),
        new FrameworkPropertyMetadata(0.0,
        FrameworkPropertyMetadataOptions.AffectsMeasure));

    public double X1
    {
        set { SetValue(X1Property, value); }
        get { return (double)GetValue(X1Property); }
    }

    // Specify the Y1 dependency property:
    public static readonly DependencyProperty Y1Property =
        DependencyProperty.Register("Y1",
        typeof(double), typeof(MyShape),
        new FrameworkPropertyMetadata(0.0,
        FrameworkPropertyMetadataOptions.AffectsMeasure));

    public double Y1
    {
        set { SetValue(Y1Property, value); }
        get { return (double)GetValue(Y1Property); }
    }

    /*Some other Dependency Properties....   and*/

    protected override Geometry DefiningGeometry
    {
        get
        {
            GeometryGroup geometryGroup = new GeometryGroup();
            line.StartPoint = new Point(X1, Y1);
            line.EndPoint = new Point(X2, Y2);
            text.SetFontWeight(FontWeights.ExtraLight);
            Geometry geometry = text.BuildGeometry(new Point((X1 + X2) / 2, (Y1 + Y2) / 2));
            geometryGroup.Children.Add(geometry);
            geometryGroup.Children.Add(line);
            return geometryGroup;
        }
    }
}


推荐答案

尝试使用 FrameworkPropertyMetadataOptions.AffectsRender

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

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