Exploring the XamlDirect APIs for middleware authors
There are times when developers must create some UI elements at runtime. Maybe you need to dynamically add a section to a page and the content of that section is data dependent, meaning you cannot create the structure for the UI in XAML at design time. One way to handle creating a dynamic UI is by simply creating new instances of the necessary objects, and then adding them to whichever layout element their parent will be in. This will work, but Microsoft has created a more performant way to achieve this.
The XamlDirect APIs are a part of the Microsoft.UI.Xaml.Core.Direct
namespace. These APIs provide greater performance when working with UI objects by providing access to XAML at a more primitive level. To demonstrate how XamlDirect can be used, let's create the same three child elements of a StackPanel
in three different ways:
- Created in XAML
- Instantiated in code
- Created with XamlDirect
We are going...