Avalonia开发实践(三)——实现GroupBox

一、开发背景

近期在项目中要用到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,但似乎到今日仍未解决。。。

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控件就开发完成了!

上一篇:Avalonia开发实践(二)——开发带边框的Grid

下一篇:Avalonia开发实践(四)——关于Setter优先级的问题

<think> 嗯,用户需要的是Avalonia框架中实现可输入框的ComboBox控件的实战实例。根据用户提供的站内引用材料来看,引用[1]和引用[4]特别有价值,它们展示了ComboBox的不同用法。 引用[1]主要演示了MVVM模式下通过ObservableCollection绑定数据源的方式。这里有个有趣的细节:在AddCom方法里重建了整个ObservableCollection实例,其实更高效的做法是直接操作ComboxArr集合。不过这个示例很好地说明了如何通过RaisePropertyChanged通知UI更新。 引用[4]的代码更接近传统WinForms的写法,直接在代码后台操作ComboBoxItem对象。其中处理选中项的方式很实用,特别是用Tag属性存储额外数据的技巧。不过这段代码没有体现可编辑特性。 用户真正想要的是带输入功能的ComboBox,这需要结合AutoCompleteBox的功能。有趣的是,Avalonia有内置的AutoCompleteBox控件,但用户可能不知道这个细节。我应该在回答中强调这个重要信息。 考虑到实际开发场景,建议用户优先采用MVVM模式实现。需要重点说明个关键点:如何设置IsEditable属性启用编辑功能,如何处理输入验证,以及如何实现自动补全的数据过滤。引用[1]中的ObservableCollection绑定机制正好可以作为数据源的基础。 用户可能是正在开发Avalonia应用的开发者,遇到需要增强ComboBox功能的需求。ta专门提到"实战实例",说明需要可直接落地的代码方案,因此示例代码要确保完整可运行。另外可以预见到,用户在实现过程中可能会遇到绑定同步或输入验证的问题,所以相关问题部分要提前准备好这些延伸内容。 </think> 在 Avalonia实现可编辑的 `ComboBox`(即允许用户输入自定义值),你需要使用 `AutoCompleteBox` 控件或其变体。标准的 `ComboBox` 主要支持从预设项中选择。以下是基于官方文档和常见实践的两种实战实现方法: --- ### 方法一:使用 `AutoCompleteBox` (推荐) `AutoCompleteBox` 专为可编辑下拉框设计,支持输入、自动补全和添加新项。 ```xml <!-- 在 axaml 文件中 --> <StackPanel Margin="20"> <!-- IsTextCompletionEnabled: 输入时自动匹配已有项 --> <AutoCompleteBox Name="EditableComboBox" IsTextCompletionEnabled="True" Watermark="输入或选择..." ItemsSource="{Binding ComboxArr}" FilterMode="Contains"/> </StackPanel> ``` ```csharp // ViewModel 代码示例 public class MainWindowViewModel : INotifyPropertyChanged { public ObservableCollection<string> ComboxArr { get; set; } public MainWindowViewModel() { ComboxArr = new ObservableCollection<string> { "Apple", "Banana", "Cherry", "Durian" }; } public event PropertyChangedEventHandler? PropertyChanged; protected void RaisePropertyChanged([CallerMemberName] string? propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } ``` #### 关键特性: 1. **输入自由**:用户可直接输入任意文本。 2. **自动过滤**:设置 `FilterMode="Contains"` 或 `"StartsWith"` 实时匹配项。 3. **添加新项**:通过 `TextSubmitted` 事件捕获新输入: ```csharp EditableComboBox.TextSubmitted += (s, e) => { if (!ComboxArr.Contains(e.Text)) ComboxArr.Add(e.Text); }; ``` --- ### 方法二:扩展 `ComboBox` (自定义程度高) 通过设置 `IsEditable=true` 启用编辑模式,需手动处理输入逻辑: ```xml <ComboBox Name="CustomEditableCombo" IsEditable="True" ItemsSource="{Binding ComboxArr}" Text="{Binding InputText, Mode=TwoWay}"/> <!-- 绑定输入文本 --> ``` ```csharp // ViewModel 增加处理逻辑 private string _inputText = ""; public string InputText { get => _inputText; set { _inputText = value; // 输入时动态过滤项(可选) FilteredItems = new ObservableCollection<string>( ComboxArr.Where(item => item.Contains(value))); RaisePropertyChanged(); } } // 添加按钮命令:将输入值加入数据源 public void AddInputToItems() { if (!string.IsNullOrEmpty(InputText) && !ComboxArr.Contains(InputText)) { ComboxArr.Add(InputText); InputText = ""; // 清空输入框 } } ``` #### 注意事项: 1. **事件处理**:需监听 `KeyDown` 事件(如按 Enter 添加新项)。 2. **项匹配**:编辑时下拉列表不会自动筛选,需手动实现过滤逻辑(如上述 `FilteredItems`)。 --- ### 对比总结 | **方案** | **优点** | **适用场景** | |--------------------|------------------------------|--------------------------| | `AutoCompleteBox` | 内置过滤/补全,开箱即用 | 需要自动补全的搜索型输入 | | 可编辑 `ComboBox` | 完全控制行为,无缝集成原控件 | 需深度自定义交互逻辑 | > **实战建议**:优先使用 `AutoCompleteBox` 满足多数可输入需求,其行为更符合用户预期且维护简单[^1][^4]。若涉及复杂验证或动态项生成(如数据库查询),可编辑 `ComboBox` 的灵活性更有优势。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值