--- name: avalonia-data-binding description: Comprehensive guide to data binding patterns in Avalonia for AI agents. license: MIT compatibility: opencode metadata: audience: avalonia-developers framework: avalonia --- # Data Binding in Avalonia Comprehensive guide to data binding patterns in Avalonia for AI agents. ## What I do - Guide implementation of ViewModels with ObservableObject base class - Show how to create observable properties with [ObservableProperty] attribute - Demonstrate command patterns with [RelayCommand] including async and CanExecute - Explain View-ViewModel mapping using DataTemplates (critical for navigation) - Show dependency injection patterns for passing services to ViewModels ## When to use me Use this skill when you need to: - Create new ViewModels for Avalonia views - Implement observable properties that notify the UI of changes - Add commands to handle user interactions (button clicks, etc.) - Set up navigation patterns with DataTemplates and ContentControl # Data Binding in Avalonia Comprehensive guide to data binding patterns in Avalonia for AI agents. ## Binding Modes ### OneWay Binding ```xml ``` ### TwoWay Binding ```xml ``` **ViewModel:** ```csharp [ObservableProperty] private string _userName = ""; [ObservableProperty] private double _volume = 50; [ObservableProperty] private bool _isEnabled = true; ``` ### OneTime Binding ```xml ``` ### OneWayToSource Binding ```xml ``` ### When to use each Use: - **OneWay**: Display data that changes infrequently - **TwoWay**: User input controls (TextBox, Slider, CheckBox) - **OneTime**: Static data that won't change after load - **OneWayToSource**: When UI updates ViewModel but not the other way ## Binding Paths ### Simple Property ```xml ``` ```csharp [ObservableProperty] private string _name = "John"; ``` ### Nested Property ```xml ``` ```csharp [ObservableProperty] private Person _person = new(); public class Person { public Address Address { get; set; } = new(); } public class Address { public string Street { get; set; } = ""; } ``` ### Collection Indexer ```xml ``` ```csharp public ObservableCollection Items { get; } = new(); public ObservableCollection Users { get; } = new(); ``` ### Attached Property ```xml ``` ### Current Item ```xml ``` ## Binding Sources ### DataContext (Default) ```xml ``` ### Element Binding ```xml ``` ### Relative Source - Parent ```xml ``` ### Relative Source - Self ```xml