Binding from Code
Binding from code in Avalonia works somewhat differently to WPF/UWP. At the low level, Avalonia's binding system is based on Reactive Extensions' IObservable
which is then built upon by XAML bindings (which can also be instantiated in code).
Subscribing to Changes to a Property
You can subscribe to changes on a property by calling the GetObservable
method. This returns an IObservable<T>
which can be used to listen for changes to the property:
var textBlock = new TextBlock();
var text = textBlock.GetObservable(TextBlock.TextProperty);
Each property that can be subscribed to has a static readonly field called [PropertyName]Property
which is passed to GetObservable
in order to subscribe to the property's changes.
IObservable
(part of Reactive Extensions, or rx for short) is out of scope for this guide, but here's an example which uses the returned observable to print a message with the changing property values to the console:
var textBlock = new TextBlock();
var text = textBlock.GetObservable(TextBlock.TextProperty);
text.Subscribe(value => Console.WriteLine(value + " Changed"));
When the returned observable is subscribed, it will return the current value of the property immediately and then push a new value each time the property changes. If you don't want the current value, you can use the rx Skip
operator:
var text = textBlock.GetObservable(TextBlock.TextProperty).Skip(1);