我有一個自定義的WPF控件MyLine,它應該代表中間沒有文字。在形狀中添加文本
public class MyLine : Shape
{
public double X1, Y1, X2, Y2;
public bool IsTextDisplayed;
public string Caption;
protected override System.Windows.Media.Geometry DefiningGeometry
{
get
{
var geometryGroup = new GeometryGroup();
if (IsTextDisplayed)
{
// calculate text point
var midPoint = new Point((X1 + X2)/2.0, (Y1 + Y2)/2.0);
// add a TextBlock with the Caption text in that point
// ???
}
// Add line
geometryGroup.Children.Add(new LineGeometry(
new Point(X1, Y1), new Point(X2, Y2)));
return geometryGroup;
}
}
}
我應該如何在這裏添加一個TextBlock(或標籤)?
我試着在裏面添加一個FormattedText
,但是這是NOK,因爲它用線條畫筆畫了文字,並且不可能讀取某些東西。
編輯
添加視覺兒童
public MyLine() : base()
{
textBlock = new System.Windows.Controls.TextBlock();
textBlock.Visibility = System.Windows.Visibility.Hidden;
this.AddVisualChild(textBlock);
}
protected override System.Windows.Media.Geometry DefiningGeometry
{
get
{
...
if (IsTextDisplayed)
{
var midPoint = new Point((X1 + X2)/2.0, (Y1 + Y2)/2.0);
string text = "some custom text";
Canvas.SetLeft(textBlock, midPoint.X);
Canvas.SetBottom(textBlock, midPoint.Y);
textBlock.Text = text;
this.textBlock.Visibility = System.Windows.Visibility.Visible;
}
else
{
this.textBlock.Visibility = System.Windows.Visibility.Hidden;
}
我沒有看到任何標籤...「/
EDIT2
添加裝飾器
public MyLine() : base()
{
this.Loaded += new RoutedEventHandler(MyLine_Loaded);
}
void MyLine_Loaded(object sender, RoutedEventArgs e)
{
AdornerLayer aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
aLayer.Add(new TextAdorner(this));
}
class TextAdorner : Adorner
{
public TextAdorner(UIElement adornedElement) : base(adornedElement)
{ }
protected override void OnRender(DrawingContext drawingContext)
{
MyLine segment = (this.AdornedElement as MyLine);
if (segment != null && segment.IsLabelUsed)
{
Rect segmentBounds = new Rect(segment.DesiredSize);
FormattedText ft = new FormattedText(
"654 m", Thread.CurrentThread.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface("Arial"), 12, Brushes.White);
drawingContext.DrawText(ft, segmentBounds.BottomRight);
}
}
}
現在,ap父母代碼永遠不會進入OnRender裝飾器方法...
我希望你的畫布的backgroundColor是不是白... – VRage 2017-10-12 11:05:15