我曾经做过类似的事情:在 UserControl 上绘制网格线,然后在其上添加控件。这是一个简单的调度程序应用程序,用于分配谁将在当月工作什么班次。我必须有列标题(天)和行标题(人)和一个可滚动的网格,我可以在其中添加/删除控件。我不知道我的解决方案能在多大程度上帮助您,但就是这样。
我使用来自here 的HeaderedScrollViewer。 UCHeader 是一个 UserControl,带有旋转的带有日期的文本框。奇迹发生在UC_GridLines。
<Grid>
<lib:HeaderedScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Background="AliceBlue">
<lib:HeaderedScrollViewer.TopHeader>
<lib:UCHeader Name="ucHeader"/>
</lib:HeaderedScrollViewer.TopHeader>
<lib:HeaderedScrollViewer.LeftHeader>
<Border BorderBrush="Black" BorderThickness="1,2,1,1">
<StackPanel Orientation="Vertical" Name="spRows" />
</Border>
</lib:HeaderedScrollViewer.LeftHeader>
<Grid Name="gridContentAll">
<Border Canvas.ZIndex="1" Background="Transparent"
BorderThickness="1,1,1,2" BorderBrush="Transparent">
<Grid ClipToBounds="True" Name="gridContent" Background="Transparent" />
</Border>
<Border Canvas.ZIndex="0" BorderThickness="1,1,1,2" BorderBrush="Black" Background="White">
<lib:UC_GridLines Name="ucGridLines" BorderThickness="0"/>
</Border>
</Grid>
</lib:HeaderedScrollViewer>
</Grid>
重要的是:
- 为包含子控件的控件设置
Background="Transparent"
- 正确设置 ZIndex,使控件显示在网格上。
- 在根元素(例如窗口)上设置
SnapsToDevicePixels="True" 和 UseLayoutRounding="True"
.xaml 文件中的 UC_GridLines 没有任何内容(只有 <Grid></Grid>)。绘制网格线发生在代码隐藏中:
protected override void OnRender(DrawingContext drawingContext)
{
// VM contains data of the grid, used to draw gridlines
// such as number of days etc.
if (this.VM == null)
{
base.OnRender(drawingContext);
return;
}
double dpiFactor = 1;
try
{
Matrix m = PresentationSource.FromVisual(this)
.CompositionTarget.TransformToDevice;
dpiFactor = 1 / m.M11;
}
catch { }
Pen pen = new Pen(Brushes.Black, 1 * dpiFactor);
double halfPenWidth = pen.Thickness / 2;
GuidelineSet guidelines = new GuidelineSet();
double width = this.VM.Days.Count * this.VM.DayWidth - 16 * (this.VM.DayWidth / 24);
double height = this.VM.RowHeight * rowCount;
for (int i = 1; i < this.VM.Days.Count; i++)
{
guidelines.GuidelinesX.Add(i * this.VM.DayWidth + halfDashPenWidth);
}
for (int i = 1; i < rowCount; i++)
{
guidelines.GuidelinesY.Add(i * this.VM.RowHeight + halfPenWidth);
}
drawingContext.PushGuidelineSet(guidelines);
for (int i = 1; i < this.VM.Days.Count; i++)
{
drawingContext.DrawLine(dashpen, new Point(i * this.VM.DayWidth, 0), new Point(i * this.VM.DayWidth, height));
}
for (int i = 1; i < rowCount; i++)
{
drawingContext.DrawLine(pen, new Point(0, i * this.VM.RowHeight), new Point(width, i * this.VM.RowHeight));
}
drawingContext.Pop();
}