在我看來,畫布絕對是錯誤的方法。
我強烈建議查找裝飾者。您可以創建一個自定義裝飾器來完成此操作。
Adorner基本上是一個「非交互式窗口」,位於所有UIElements之上。它允許你做任何你想要的東西(創建控件,繪製東西等等),它將出現在控件本身之上。
用一塊透明玻璃在上面畫一張木製咖啡桌。如果您在透明玻璃上畫畫,您仍然可以看到茶几。唯一的區別是,你實際上可以直接通過咖啡桌上的透明玻璃並觸摸木材本身。
我討厭發佈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));
}
}
}
}
如果你想我更詳細地說明代碼本身讓我知道。
我確認這會在您的主頁上繪製一個網格。你仍然應該能夠與下面的內容進行交互。
哇我剛剛意識到這是從2009年11月 – tronious 2013-09-11 14:40:14