在 Avalonia 中实现数据绑定,核心是让 UI 元素自动响应数据模型的变化,同时支持用户输入反向更新模型——这靠的是 INotifyPropertyChanged 接口 + XAML 中的 Binding 语法,和 WPF 类似但更轻量。
1. 让数据模型支持属性变更通知
绑定的前提是 ViewModel 能“告诉”界面“我变啦”。最常用方式是实现
INotifyPropertyChanged接口,并在属性 setter 中触发
PropertyChanged事件。
推荐用 Avalonia.PropertyChanged NuGet 包(或手动实现),或直接继承 Avalonia 提供的基类
ReactiveObject(需引用
Avalonia.Base):
public class MainViewModel : ReactiveObject
{
private string _name = "张三";
public string Name
{
get => _name;
set => this.RaiseAndSetIfChanged(ref _name, value);
}
private int _age;
public int Age
{
get => _age;
set => this.RaiseAndSetIfChanged(ref _age, value);
}
}
✅
RaiseAndSetIfChanged会自动比较新旧值、触发通知、并更新字段,省去手写事件代码。
2. 在 XAML 中声明 Binding
先在窗口或用户控件中设置
DataContext,再用
{Binding PropertyName} 绑定到属性。默认是 TwoWay(双向),但仅对可编辑控件(如 TextBox、Slider)生效;TextBlock 默认是 OneWay。
示例(MainWindow.axaml):
<Window xmlns="https://github.com/avaloniaui">
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<StackPanel Margin="20">
<TextBox Text="{Binding Name}" PlaceholderText="请输入姓名" />
<TextBlock Text="{Binding Age, StringFormat='年龄:{0}岁'}" />
<Slider Value="{Binding Age}" Minimum="0" Maximum="120" />
</StackPanel>
</Window>
? 小技巧:
用StringFormat格式化显示(仅限 OneWay 或 OneTime 绑定) 绑定失败时,Avalonia 会在输出窗口打印警告(比如属性名拼错、DataContext 为空),记得看输出面板 路径支持嵌套,如
{Binding User.Profile.NickName}
3. 命令绑定:把按钮点击连到方法
用
ICommand实现交互逻辑解耦。推荐使用 Avalonia 内置的
ReactiveCommand(配合 ReactiveUI)或轻量的
RelayCommand(来自
Avalonia.Controls)。
在 ViewModel 中定义:
public ICommand SayHelloCommand { get; }
public MainViewModel()
{
SayHelloCommand = new RelayCommand(() =>
{
Console.WriteLine($"你好,{Name}!");
}, () => !string.IsNullOrWhiteSpace(Name)); // 可选:启用条件
}
XAML 中绑定:
<Button Content="打招呼" Command="{Binding SayHelloCommand}" />
✅ 命令自动根据
CanExecute状态控制按钮是否可用(无需手动写 IsEnabled 绑定)。
4. 集合绑定与列表展示
要绑定列表(如显示用户列表),用
ObservableCollection<t></t>—— 它实现了
INotifyCollectionChanged,能响应增删改。
ViewModel 中:
private ObservableCollection<string> _items = new() { "苹果", "香蕉", "橙子" };
public ObservableCollection<string> Items => _items;
XAML 中用
ItemsControl或
ListBox:
<ListBox Items="{Binding Items}" />
如需自定义每一项样式,加
ItemTemplate:
<ListBox Items="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Foreground="Blue" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
基本上就这些。Avalonia 数据绑定不复杂但容易忽略细节:确保 DataContext 设置正确、属性名大小写一致、集合用 ObservableCollection、命令用 ICommand。跑通一个 TextBox + ViewModel 的双向绑定,后面就一通百通了。
