问题
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;
}
}
}
回答1:
Try to use FrameworkPropertyMetadataOptions.AffectsRender
来源:https://stackoverflow.com/questions/5458802/how-to-properly-refresh-a-custom-shape-in-wpf