-1

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?

1 Answer 1

1

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.
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, unfortunately this toolkit is not compatible with my system: net8.0-windows10.0.19041. Perhaps because that is UWP and my App is developed as WinUI App
CommunityToolkit.WinUI.UI.FrameworkElementExtensions did the trick, exactly what I needed, thank you for the direction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.