Avalonia怎么创建一个UserControl Avalonia用户控件使用教程

来源:这里教程网 时间:2026-02-21 17:35:46 作者:

在 Avalonia 中创建 UserControl 很简单,核心是继承

UserControl
类,并用 XAML 定义界面、C# 定义逻辑。

新建 UserControl 文件

在项目中右键 → “添加” → “新建项”,选择 Avalonia User Control(如果没看到,选“类”或“空文件”,手动命名 + 添加代码)。

推荐方式:使用 Visual Studio 或 Rider 的 Avalonia 模板插件,会自动生成带 XAML 和 .cs 的配套文件,例如:

MyButton.xaml
(XAML 界面)
MyButton.xaml.cs
(后台逻辑,继承
UserControl

XAML 中正确声明命名空间和根元素

确保 XAML 文件顶部有正确的 xmlns 声明,并以

UserControl
为根元素:

<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" x:Class="MyApp.Controls.MyButton">
    <Border Background="LightBlue" Padding="10">
        <TextBlock Text="{Binding Label}" />
    </Border>
</UserControl>

注意:

x:Class
必须与 .cs 文件中的类名和命名空间完全一致。

后台代码继承 UserControl 并支持绑定

MyButton.xaml.cs
中,确保类继承
UserControl
,并可选地定义依赖属性或绑定源:

namespace MyApp.Controls
{
    public partial class MyButton : UserControl
    {
        public static readonly StyledProperty<string> LabelProperty =
            AvaloniaProperty.Register<MyButton, string>(nameof(Label));
<pre class="brush:php;toolbar:false;">    public string Label
    {
        get => GetValue(LabelProperty);
        set => SetValue(LabelProperty, value);
    }
    public MyButton()
    {
        InitializeComponent();
    }
}

}

这样你就能在父界面中像这样使用它:

<local:MyButton Label="点我试试" />

其中

local
是你在父 XAML 中声明的命名空间前缀,例如:
xmlns:local="using:MyApp.Controls"

在主窗口或页面中使用 UserControl

在使用前,先在目标 XAML 文件顶部引入命名空间:

xmlns:local="using:MyApp.Controls"

然后直接当作普通控件使用,支持样式、绑定、事件等:

<local:MyButton Label="{Binding Title}" Click="OnMyButtonClick" />

如果需要处理点击事件,在 .cs 中添加方法:

private void OnMyButtonClick(object sender, RoutedEventArgs e)
{
    // 自定义逻辑
}

基本上就这些 —— 不复杂但容易忽略命名空间和 x:Class 匹配。写完记得编译一次,Avalonia 会自动生成

InitializeComponent()
的分部实现。

相关推荐