您可以創建自己的Grid
來繪製線條本身。
<wpfApplication5:MyGrid ShowGridLines="True">
<wpfApplication5:MyGrid.GridLinesPen>
<Pen Brush="DeepSkyBlue" Thickness="5" />
</wpfApplication5:MyGrid.GridLinesPen>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</wpfApplication5:MyGrid>
而後面的代碼:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApplication5
{
public class MyGrid : Grid
{
public new static readonly DependencyProperty ShowGridLinesProperty = DependencyProperty.Register(
"ShowGridLines", typeof (bool), typeof (MyGrid), new PropertyMetadata(default(bool)));
public static readonly DependencyProperty GridLinesPenProperty = DependencyProperty.Register(
"GridLinesPen", typeof (Pen), typeof (MyGrid),
new FrameworkPropertyMetadata(default(Pen), FrameworkPropertyMetadataOptions.AffectsRender));
public new bool ShowGridLines
{
get { return (bool) GetValue(ShowGridLinesProperty); }
set { SetValue(ShowGridLinesProperty, value); }
}
public Pen GridLinesPen
{
get { return (Pen) GetValue(GridLinesPenProperty); }
set { SetValue(GridLinesPenProperty, value); }
}
protected override void OnRender(DrawingContext dc)
{
Pen pen = GridLinesPen;
if (pen != null)
{
ColumnDefinitionCollection columnDefinitions = ColumnDefinitions;
if (columnDefinitions.Count > 1)
{
for (int i = 1; i < columnDefinitions.Count; i++)
{
ColumnDefinition columnDefinition = columnDefinitions[i];
double offset = columnDefinition.Offset;
dc.DrawLine(pen, new Point(offset, 0), new Point(offset, RenderSize.Height - 1));
}
}
RowDefinitionCollection rowDefinitions = RowDefinitions;
if (rowDefinitions.Count > 1)
{
for (int i = 1; i < rowDefinitions.Count; i++)
{
RowDefinition rowDefinition = rowDefinitions[i];
double offset = rowDefinition.Offset;
dc.DrawLine(pen, new Point(0, offset), new Point(RenderSize.Width - 1, offset));
}
}
}
base.OnRender(dc);
}
}
}
注:加入new
到ShowGridLines
我繞過該屬性的原始行爲。
這種方法的問題是,如果OP使用ItemsControl,那麼每個元素都應該在網格中填充它們可能不需要的單元格,然後他可以使用ItemContainerTemplate輕鬆完成:http://msdn.microsoft。 COM/EN-US /庫/ system.windows.controls.itemcontainertemplate(v = vs.110)的.aspx。 – Aybe
確實如此,但他的繪圖確實顯示了一個uniformgrid –