How to set status of control from OnLaunched in C++/WinRT app?

Steven Brown 26 Reputation points
2025-06-27T21:53:30.9633333+00:00

In Visual Studio I compiled the blank C++/WinRT UWP app which displays a button that says "Click me" and "Clicked" after it is clicked. As an experiment to learn how to initialize a control according to user settings, I copied the following line from ClickHandler in MainPage.cpp

myButton().Content(box_value(L"Clicked"));

and pasted it as the last line of OnLaunched in App.cpp. The idea is that if that works, the application when launched will display "Clicked" in the button even before it is clicked. The problem is, when I try to compile the program, I get "error C3861: 'myButton': identifier not found."

"myButton" is recognized by the compiler in MainPage.cpp but not in App.cpp. I thought that might be because a header file or a "using namespace" statement needs to be included in App.cpp. To my surprise, the only #include in MainPage.cpp that is not in App.cpp is #include "MainPage.g.cpp", and the two namespace statements, "using namespace winrt;" and "using namespace Windows::UI::Xaml;" are both in App.cpp. So, I copied and pasted #include "MainPage.g.cpp" into App.cpp, but the compiler still reports "myButton': identifier not found."

My first question is, how can I make the complier recognize "myButton" as a valid identifier? My second question is, if there is no way to make the complier recognize "myButton", is there any way to initialize a control to anything besides its default condition?

Developer technologies Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2025-06-28T05:01:51.1333333+00:00

    In short, open the MainPage in Designer, add a handler for Loading or Loaded event, write your code inside the generated event handler.

    I do not think that the button is available inside the OnLaunched.

    Alternatively, edit the MainPage.h file, add this function to MainPage struct:

    void InitializeComponent( ) 
    {
        MainPageT::InitializeComponent( );
    
        myButton( ).Content( box_value( L"Click" ) );
    }
    

    (https://github.com/microsoft/cppwinrt/tree/master/nuget#initializecomponent)

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.