我有一个 ItemsControl,它使用 aGrid
作为ItemsPanelTemplate
,并在 Grid.Column 和 Grid.Row 上设置ItemContainerStyle
以在网格中定位数据项
有没有办法将 GridLines 添加到网格中,或者用边框填充空白单元格?
现在我已经ShowGridLines
设置为 True 虚线,但是我希望显示水平线,我更喜欢实心 GridLines
有相当多的 XAML,但这里是我的 XAML 布局的屏幕截图:
抱歉,无法设置网格线的样式。至少不是以简单的方式。请参阅以下问题以获取解释:如何更改 WPF 中网格的网格线颜色?
MSDN 文档说“只有虚线可用,因为此属性旨在用作调试布局问题的设计工具,而不是用于生产质量代码。如果您希望网格内的线条,请将网格内的元素设置为具有边框。”
编辑:如果你想要边框,你可以创建一个自定义Grid
并绘制控件的GridLines
inOnRender
方法。
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace BorderGridControl
{
public class GridControl : Grid
{
#region Properties
public bool ShowCustomGridLines
{
get { return (bool)GetValue(ShowCustomGridLinesProperty); }
set { SetValue(ShowCustomGridLinesProperty, value); }
}
public static readonly DependencyProperty ShowCustomGridLinesProperty =
DependencyProperty.Register("ShowCustomGridLines", typeof(bool), typeof(GridControl), new UIPropertyMetadata(false));
public Brush GridLineBrush
{
get { return (Brush)GetValue(GridLineBrushProperty); }
set { SetValue(GridLineBrushProperty, value); }
}
public static readonly DependencyProperty GridLineBrushProperty =
DependencyProperty.Register("GridLineBrush", typeof(Brush), typeof(GridControl), new UIPropertyMetadata(Brushes.Black));
public double GridLineThickness
{
get { return (double)GetValue(GridLineThicknessProperty); }
set { SetValue(GridLineThicknessProperty, value); }
}
public static readonly DependencyProperty GridLineThicknessProperty =
DependencyProperty.Register("GridLineThickness", typeof(double), typeof(GridControl), new UIPropertyMetadata(1.0));
#endregion
protected override void OnRender(DrawingContext dc)
{
if (ShowCustomGridLines)
{
foreach (var rowDefinition in RowDefinitions)
{
dc.DrawLine(new Pen(GridLineBrush, GridLineThickness), new Point(0, rowDefinition.Offset), new Point(ActualWidth, rowDefinition.Offset));
}
foreach (var columnDefinition in ColumnDefinitions)
{
dc.DrawLine(new Pen(GridLineBrush, GridLineThickness), new Point(columnDefinition.Offset, 0), new Point(columnDefinition.Offset, ActualHeight));
}
dc.DrawRectangle(Brushes.Transparent, new Pen(GridLineBrush, GridLineThickness), new Rect(0, 0, ActualWidth, ActualHeight));
}
base.OnRender(dc);
}
static GridControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(GridControl), new FrameworkPropertyMetadata(typeof(GridControl)));
}
}
}
我试过了,它似乎工作得很好。
这里是一个使用示例:
<controls:GridControl ShowCustomGridLines="True"
GridLineBrush="Red"
GridLineThickness="1">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
</controls:GridControl>