Search code examples
avaloniauiavalonia

Equivalent of a React component in Avalonia?


I am a fluent React.js developer and I'm trying to pick up Avalonia (I do have C# experience), but I'm really confused about how to encapsulate common reusable pieces of UI like React makes so easy. I see TemplatedControl, UserControl, and CustomControl, but all the examples seem to treat these as different ways to make custom single control elements, not fragments of several elements together. I can't find an example of a TemplatedControl or UserControl that encapsulates more than one single UI control. I am not trying to draw my own custom UI controls from scratch, I want to build controls that consist of multiple other existing controls.

What is the equivalent in Avalonia to components in React? How can I make a class with an AXAML file to go with it that can contain multiple UI elements together, accept properties as inputs, and expose custom events for receiving output?

Sorry if this is a bad question but all the docs are explained in terms of WPF, which I have no experience with. The Avalonia.Samples repo examples that seem to show this off look like a huge amount of code for what look to be really simple things, so I'm not even sure if I'm reading it right.


Solution

  • How can I make a class with an AXAML file to go with it that can contain multiple UI elements together, accept properties as inputs, and expose custom events for receiving output?

    That is a UserControl. See Choosing A Custom Control Type:

    A UserControl is a high-level approach for creating custom controls in Avalonia. It allows you to compose a control by combining existing controls and defining the layout using XAML. A UserControl acts as a container that encapsulates multiple controls and provides a cohesive user interface.


    If you create a new Visual Studio Project by the Avalonia C# Project template, and select Desktop as the target platform, the template generates two view elements in the Views folder of the project. One of them is the MainWindow, the other is called MainView and is a UserControl. This is where you can start.