既然你想在视觉上装饰文本框,我想到的第一件事就是恰当地命名为Adnorner。
我写了一个快速演示来展示如何装饰文本框。画线部分很容易,棘手的部分是弄清楚应该在哪里画线。我在示例中对行位置进行了硬编码。我想你必须做一些文本测量来找出你的文本有多高(对于行高)以及 50 个字符的价值是多少(以抵消你的行)。
这是xaml:
<Window x:Class="WpfApplication4.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">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<AdornerDecorator>
<TextBox TextWrapping="Wrap" AcceptsReturn="True" x:Name="myTextBox" Width="200px" Height="200px">hello</TextBox>
</AdornerDecorator>
</Grid>
</Window>
以及背后的代码
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AdornerLayer myAdornerLayer = AdornerLayer.GetAdornerLayer(myTextBox);
myAdornerLayer.Add(new LineAdorner(myTextBox));
}
// Adorners must subclass the abstract base class Adorner.
#region Nested type: LineAdorner
public class LineAdorner : Adorner
{
// Be sure to call the base class constructor.
public LineAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
// A common way to implement an adorner's rendering behavior is to override the OnRender
// method, which is called by the layout system as part of a rendering pass.
protected override void OnRender(DrawingContext drawingContext)
{
var adornedElementRect = new Rect(AdornedElement.DesiredSize);
var renderPen = new Pen(new SolidColorBrush(Colors.Red), 1.5);
// Draw lines.
drawingContext.DrawLine(renderPen,
new Point(adornedElementRect.TopLeft.X + 75, adornedElementRect.TopLeft.Y),
new Point(adornedElementRect.TopLeft.X + 75, adornedElementRect.TopLeft.Y + 20));
drawingContext.DrawLine(renderPen,
new Point(adornedElementRect.TopLeft.X + 120, adornedElementRect.TopLeft.Y + 20),
new Point(adornedElementRect.TopLeft.X + 120, adornedElementRect.TopLeft.Y + 40));
drawingContext.DrawLine(renderPen,
new Point(adornedElementRect.TopLeft.X + 120, adornedElementRect.TopLeft.Y + 40),
new Point(adornedElementRect.TopLeft.X + 120, adornedElementRect.TopLeft.Y + 60));
}
}
#endregion
}
}