在我看来,画布绝对是错误的方法。
我强烈建议查找 Adorners。您可以创建一个自定义装饰器来执行此操作。
Adorner 基本上是位于所有 UIElement 之上的“非交互式窗口”。它允许你做任何你想做的事情(创建控件,绘制东西,等等),它们会出现在控件本身的顶部。
想象一张木制咖啡桌,上面放着一块透明玻璃。如果你在透明玻璃上画画,你仍然可以看到咖啡桌。唯一的区别是您实际上可以直接穿过咖啡桌上的透明玻璃并触摸木头本身。
我讨厌发布 MSDN 链接……但是……嗯。在这种情况下,这将是一个好的开始:
http://msdn.microsoft.com/en-us/library/ms743737.aspx
编辑:
我迅速把东西扔到一起。希望这有帮助吗?
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<loc:GridWithRulerxaml></loc:GridWithRulerxaml>
<Button Height="20" Width="50" >Click me</Button>
<TextBox Width="150" Height="25" HorizontalAlignment="Left">This is a text box</TextBox>
</Grid>
</Window>
用户控制:
<UserControl x:Class="WpfApplication1.GridWithRulerxaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
用户控制代码隐藏:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for GridWithRulerxaml.xaml
/// </summary>
public partial class GridWithRulerxaml : UserControl
{
public GridWithRulerxaml()
{
InitializeComponent();
//Loaded event is necessary as Adorner is null until control is shown.
Loaded += GridWithRulerxaml_Loaded;
}
void GridWithRulerxaml_Loaded(object sender, RoutedEventArgs e)
{
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
var rulerAdorner = new RulerAdorner(this);
adornerLayer.Add(rulerAdorner);
}
}
}
最后是装饰器本身:
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApplication1
{
public class RulerAdorner : Adorner
{
private FrameworkElement element;
public RulerAdorner(UIElement el) : base(el)
{
element = el as FrameworkElement;
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
base.OnRender(drawingContext);
double height = element.ActualHeight;
double width = element.ActualWidth;
double linesHorizontal = height/50;
double linesVertical = width/50;
var pen = new Pen(Brushes.RoyalBlue, 2) { StartLineCap = PenLineCap.Triangle, EndLineCap = PenLineCap.Triangle };
int offset = 0;
for (int i = 0; i <= linesVertical; ++i)
{
offset = offset + 50;
drawingContext.DrawLine(pen, new Point(offset, 0), new Point(offset, height));
}
offset = 0;
for (int i = 0; i <= linesHorizontal; ++i)
{
offset = offset + 50;
drawingContext.DrawLine(pen, new Point(0, offset), new Point(width, offset));
}
}
}
}
如果您希望我详细说明代码本身,请告诉我。
我确认这将在您的主页上的任何内容之上绘制一个网格。您仍然应该能够与下面的内容进行交互。