Avlonia 自定义控件

Avalonia 中使用自定义控件

在Avlonia 中自定义控件和在WPF 中类似,但在使用依赖属性注册上稍有区别

  • XAML
<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d" d:DesignWidth="400" d:DesignHeight="400"
             x:Class="CustCtrl.CircleControl" Background="Transparent">
	<Viewbox>
		<Grid Height="400" Width="400">
			<Ellipse Stroke="Blue" StrokeThickness="8" />
		</Grid>
	</Viewbox>
</UserControl>
  • CS Code
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using System;

namespace CustCtrl;

public partial class CircleControl : UserControl
{
    public CircleControl()
    {
        InitializeComponent();
    }


    public IBrush Fill
    {
        get => GetValue(FillProperty);
        set => SetValue(FillProperty, value);
    }
    static CircleControl()
    {
        AffectsRender<CircleControl>(FillProperty);
    }

    public static readonly StyledProperty<IBrush> FillProperty =
        AvaloniaProperty.Register<CircleControl, IBrush>(nameof(Fill),Brushes.Red); //这里和WPF 总Dependency.Register() 注册方法不同
    public override void Render(DrawingContext context)
    {
        base.Render(context);
        var radius = Math.Min(Bounds.Width,Bounds.Height)/2;
        var center = new Point(Bounds.Width / 2, Bounds.Height / 2);
        context.DrawEllipse(Fill,null,center,radius,radius);
    }

}
posted @ 2026-02-02 11:49  丹心石  阅读(0)  评论(0)    收藏  举报