Search code examples
c#xamlwinui-3winui

Referencing UI elements created by XAML during runtime


I am creating a WinUI 3 application, I need to manipulate one of the UI elements during runtime in a very custom and versatile way, so I don't want to define it within XAML.

To manipulate it with code I had to assign the element to a variable during runtime. To do that I had to start from my main window Content property and loop over the nested UI elements until I find the one I am looking for.

There must be a more efficient way, I know the Name of the element, but I cannot know where in the UI hierarchy it would be located, how can I reference it during runtime?


Solution

  • I don't want to define it within XAML.

    If you are creating the UI element in C#, why not keeping it in a variable?

    You can also try the FindDescendant() and FindDescendants() methods from the CommunityToolkit.WinUI.Extensions.

    MainWindow.xaml

    <Grid Loaded="RootGrid_Loaded">
        <!--  Your UI here.  -->
    </Grid>
    

    And let's say you are looking for a Button with the name "someButton".

    MainWindow.xaml.cs

    private void RootGrid_Loaded(object sender, RoutedEventArgs e)
    {
        if ((sender as Grid)?.FindDescendants()
            .OfType<Button>()
            .FirstOrDefault(button => button.Name is "someButton") is not { } someButton)
        {
            return;
        }
    
        // Your logic here.
    }