一、开发背景
近期在项目中要用到GroupBox,结果发现Avalonia原生框架中竟然没有这一控件。想着这个控件也不算复杂,索性就自己实现一个好了。
二、坑的开始
熟悉桌面开发的朋友一定对下面这个经典的GroupBox样式不陌生——
这个样式看似简单,实则也不难实现。只要解决对标题处边框的擦除或遮盖这一个小问题就可以了。在WPF中,是用了OpacityMask来实现的。而在Avalonia中,仍然保留了这一属性,使得我们能很轻松地实现控件模板的移植。
但是事实真的这样吗?
当我把GroupBox的原生模板移植到Avalonia中,并且原模原样地实现了一个BorderGapMaskConverter之后,我发现该模板并不能正常工作。于是我单独写了个关于Border边框部分遮挡的用例,才发现DrawingBrush/VisualBrush并不能给OpacityMask使用,会发生如下报错:
Unable to cast object of type 'Avalonia.Media.DrawingBrush' to type 'Avalonia.Media.IImmutableBrush
后来在github上的源码仓库下也发现有人提了相同的issue,但似乎到今日仍未解决。。。
三、开辟新思路
既然用遮罩的方式没办法实现,那不如就单纯画一个带有缺口的边框好了!
四、实现过程
1、先编写一个缺口矩形生成器,使用Geometry的图形生成指令
public static Geometry GetRoundedRectangleWithGap(Rect rect, double radiusX, double radiusY, double gapValue1, double gapValue2)
{
StreamGeometry streamGeometry = new StreamGeometry();
using (StreamGeometryContext streamGeometryContext = streamGeometry.Open())
{
var arcSize = new Size(radiusX, radiusY);
var startPoint = new Point(Math.Max(gapValue1, gapValue2), rect.Top);
var endPoint = new Point(Math.Min(gapValue1, gapValue2), rect.Top);
streamGeometryContext.BeginFigure(startPoint, true);
streamGeometryContext.LineTo(new Point(rect.Right - radiusX, rect.Top));
streamGeometryContext.ArcTo(new Point(rect.Right, rect.Top + radiusY), arcSize, PiOver2, false, SweepDirection.Clockwise);
streamGeometryContext.LineTo(new Point(rect.Right, rect.Bottom - radiusY));
streamGeometryContext.ArcTo(new Point(rect.Right - radiusX, rect.Bottom), arcSize, PiOver2, false, SweepDirection.Clockwise);
streamGeometryContext.LineTo(new Point(rect.Left + radiusX, rect.Bottom));
streamGeometryContext.ArcTo(new Point(rect.Left, rect.Bottom - radiusY), arcSize, PiOver2, false, SweepDirection.Clockwise);
streamGeometryContext.LineTo(new Point(rect.Left, rect.Top + radiusY));
streamGeometryContext.ArcTo(new Point(rect.Left + radiusX, rect.Top), arcSize, PiOver2, false, SweepDirection.Clockwise);
streamGeometryContext.LineTo(endPoint);
streamGeometryContext.EndFigure(false);
}
return streamGeometry;
}
2、再定义一个专门用来绘制GroupBox边框的控件
internal class GroupBoxBorder : Control
{
#region 私有变量
private double _gapValue1;
private double _gapValue2;
#endregion
public sealed override void Render(DrawingContext context)
{
var groupBox = this.TemplatedParent as GroupBox;
if (groupBox == null)
return;
var pen = new Pen(groupBox.BorderBrush, groupBox.BorderThickness.Top);
var streamGeometry = GeometryHelper.GetRoundedRectangleWithGap(new Rect(new Point(), Bounds.Size),
groupBox.CornerRadius.TopLeft,
groupBox.CornerRadius.TopLeft,
_gapValue1,
_gapValue2);
context.DrawGeometry(null, pen, streamGeometry);
}
internal void UpdateBorder(double gapValue1, double gapValue2)
{
_gapValue1 = gapValue1;
_gapValue2 = gapValue2;
InvalidateVisual();
}
}
3、GroupBox的模板及后台代码如下
<ControlTemplate>
<Grid RowDefinitions="Auto,Auto,*">
<Grid Grid.Row="1" Grid.RowSpan="2">
<ContentPresenter x:Name="PART_ContentPresenter"
RecognizesAccessKey="True"
Padding="{TemplateBinding Padding}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Background="{TemplateBinding Background}"
Foreground="{TemplateBinding Foreground}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
<cy:GroupBoxBorder x:Name="PART_ContentBorder"/>
</Grid>
<Border x:Name="PART_HeaderBorder"
Grid.Row="0"
Grid.RowSpan="2"
Padding="{TemplateBinding HeaderPadding}">
<ContentPresenter x:Name="PART_HeaderPresenter"
RecognizesAccessKey="True"
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
Margin="{TemplateBinding HeaderMargin}"
HorizontalAlignment="{TemplateBinding HeaderHorizontalAlignment}"
VerticalAlignment="{TemplateBinding HeaderVerticalAlignment}"/>
</Border>
</Grid>
</ControlTemplate>
/// <summary>
/// GroupBox
/// </summary>
[TemplatePart("PART_ContentBorder", typeof(GroupBoxBorder))]
[TemplatePart("PART_HeaderPresenter", typeof(ContentPresenter))]
[TemplatePart("PART_ContentPresenter", typeof(ContentPresenter))]
public class GroupBox : HeaderedContentControl
{
#region 私有变量
private GroupBoxBorder _contentBorder;
private ContentPresenter _headerPresenter;
private ContentPresenter _contentPresenter;
#endregion
#region 样式化属性
/// <summary>
/// Gets or sets the padding to place around the <see cref="HeaderedContentControl.Header"/> control.
/// </summary>
public Thickness HeaderPadding
{
get { return (Thickness)GetValue(HeaderPaddingProperty); }
set { SetValue(HeaderPaddingProperty, value); }
}
/// <summary>
/// Defines the <see cref="HeaderPadding"/> property.
/// </summary>
public static readonly StyledProperty<Thickness> HeaderPaddingProperty = AvaloniaProperty.Register<GroupBox, Thickness>("HeaderPadding", new Thickness(10, 0));
/// <summary>
/// Gets or sets the margin around the <see cref="HeaderedContentControl.Header"/> control.
/// </summary>
public Thickness HeaderMargin
{
get { return (Thickness)GetValue(HeaderMarginProperty); }
set { SetValue(HeaderMarginProperty, value); }
}
/// <summary>
/// Defines the <see cref="HeaderMargin"/> property.
/// </summary>
public static readonly StyledProperty<Thickness> HeaderMarginProperty = AvaloniaProperty.Register<GroupBox, Thickness>("HeaderMargin", new Thickness(5, 0));
/// <summary>
/// Gets or sets the horizontalAlignment of header.
/// </summary>
public HorizontalAlignment HeaderHorizontalAlignment
{
get { return (HorizontalAlignment)GetValue(HeaderHorizontalAlignmentProperty); }
set { SetValue(HeaderHorizontalAlignmentProperty, value); }
}
/// <summary>
/// Defines the <see cref="HeaderHorizontalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HeaderHorizontalAlignmentProperty = AvaloniaProperty.Register<GroupBox, HorizontalAlignment>("HeaderHorizontalAlignment", HorizontalAlignment.Left);
/// <summary>
/// Gets or sets the verticalAlignment of header.
/// </summary>
public VerticalAlignment HeaderVerticalAlignment
{
get { return (VerticalAlignment)GetValue(HeaderVerticalAlignmentProperty); }
set { SetValue(HeaderVerticalAlignmentProperty, value); }
}
/// <summary>
/// Defines the <see cref="HeaderVerticalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> HeaderVerticalAlignmentProperty = AvaloniaProperty.Register<GroupBox, VerticalAlignment>("HeaderVerticalAlignment", VerticalAlignment.Center);
#endregion
#region 重写方法
/// <summary>
/// OnApplyTemplate
/// </summary>
/// <param name="e"></param>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_contentBorder = e.NameScope.Find<GroupBoxBorder>("PART_ContentBorder");
_headerPresenter = e.NameScope.Get<ContentPresenter>("PART_HeaderPresenter");
_contentPresenter = e.NameScope.Get<ContentPresenter>("PART_ContentPresenter");
if (_contentBorder != null)
{
_headerPresenter.LayoutUpdated += (_s, _e) =>
{
_contentBorder.UpdateBorder(_headerPresenter.Bounds.Left - _headerPresenter.Margin.Left, _headerPresenter.Bounds.Right + _headerPresenter.Margin.Right);
};
}
}
#endregion
}
至此,一个基础的Avalonia框架下的GroupBox控件就开发完成了!