diff --git a/README.md b/README.md new file mode 100644 index 0000000000..ef13ce14e3 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +> **Warning** This is just a proof of concept, don't use it for production purposes! There are no unit tests in this project yet. Also, this project hasn't been extensively tested with any other app except for the `XamlNameReferenceGenerator.Sandbox` app. + +### C# `SourceGenerator` for Typed Avalonia `x:Name` References + +This is a [C# `SourceGenerator`](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/) built for generating strongly-typed references to controls with `x:Name` (or just `Name`) attributes declared in XAML (or, in `.axaml`). The sandbox app is targeting `net5` which is still in preview, so this source generator is an early proof-of-concept. The idea is that you include your Avalonia XAML files into your project via `` and then decorate your view class with `[GenerateTypedNameReferences]` and the source generator will look for the `xaml` (or `axaml`) file with the same name as your C# class. The source generator then parses the XML markup, finds all XML tags with `x:Name` attributes and generates the C# code. + +### Getting Started + +So in your project file you write the following code: + +```xml + + + %(Filename) + + + Designer + + + + +``` + +And then you reference the source generator as such: + +```xml + + + +``` + +Finally, you declare your view class as `partial` and decorate it with `[GenerateTypedNameReferences]`: + +```cs +[GenerateTypedNameReferences] // Coolstuff! +public partial class SignUpView : Window +{ + public SignUpView() + { + AvaloniaXamlLoader.Load(this); + UserNameTextBox.Text = "Joseph"; // Coolstuff! + } +} +``` + +### What do the generated sources look like? + +For the [`SignUpView` view class](https://github.com/worldbeater/XamlNameReferenceGenerator/blob/main/XamlNameReferenceGenerator.Sandbox/SignUpView.xaml#L6) from [the sandbox project](https://github.com/worldbeater/XamlNameReferenceGenerator/tree/main/XamlNameReferenceGenerator.Sandbox), we get the following generated output: + +```cs +// + +using System; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; + +namespace XamlNameReferenceGenerator.Sandbox +{ + public partial class SignUpView + { + public TextBox UserNameTextBox => this.FindControl("UserNameTextBox"); + public TextBlock UserNameValidation => this.FindControl("UserNameValidation"); + public TextBox PasswordTextBox => this.FindControl("PasswordTextBox"); + public TextBlock PasswordValidation => this.FindControl("PasswordValidation"); + public TextBox ConfirmPasswordTextBox => this.FindControl("ConfirmPasswordTextBox"); + public TextBlock ConfirmPasswordValidation => this.FindControl("ConfirmPasswordValidation"); + public Button SignUpButton => this.FindControl