WinUI3 : How to reference existing WinUI3 element programatically

Harshithraj1871 1,516 Reputation points
2023-07-28T10:21:31.9466667+00:00

Hi,

Im working on the WinUI3 desktop app in C++ programatically without using any XAML files. From creation of the App to the creation of a button is done programmatically without any XAML files.

Now suppose I have 2 Canvas in Window (Say canvas 1 and Canvas 2) and Each canvas has 1 button. Now I have to change the color of canvas 2 when the canvas 1 button is clicked. When I get the button click event from Canvas 1's button, how can I access the Canvas 2 object?

Possible solutions I came across

  1. Set an ID as the name for Canvas 2 and get the Canvas 2 reference from traversing the Visual tree
    1. Ref - https://learn.microsoft.com/en-us/answers/questions/1126470/winui3-how-to-perform-id-name-based-access-on-winu?page=1&orderby=Helpful&comment=answer-1126872#newest-answer-comment
  2. Store the Canvas 2 object somewhere and access it when the button is clicked.

Are these 2 the only valid option or does Microsoft provide any artifact to achieve this?

My issue with the above possible solutions is,

  1. Solution 1: High-time complexity
  2. Solution 2: If I want to store a WinUI3 control, I only want to store it as void pointer which can't be achieved.

Thank you.

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
752 questions
{count} votes