Access XAML controls in cpp file other than mainpage?

Ryan Gallagher 21 Reputation points
2020-08-12T19:07:38.787+00:00

I am using mainpage.cpp as a launcher basically pulling all of the inputs from the UI and packaging them into a data struct and shipping off a reference to my functions on the second .cpp file.

I have included both pch.h and mainpage.h in file B and when I try to access the control as I would in mainpage.cpp it says:
"a nonstatic member reference must be relative to a specific object"

Code:

winrt::DiceTesterUI::implementation::MainPage::TextBoxItterations().Text()

Do I need to include both pch and mainpage header files or just one to get access to pch since pch is eventually loaded by mainpage.h?

I may be in over my head and am not asking the right questions. Any help is much appreciated.

Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. Fay Wang - MSFT 5,196 Reputation points
    2020-08-13T06:59:52.217+00:00

    Hello,

    Welcome to Microsoft Q&A!

    If you do want to include the pch header file, you can include it and include MainPage header file. It dosen’t matter if the include statement is repeated, because each header file has statement “#pragma once”. Or, you can just include MainPage header file, but MainPage.h file must include pch.h.

    > Access XAML controls in cpp file other than mainpage

    If you want to access a control of the MainPage from another .cpp file, you can declare the control as a read-only property in the MainPage.idl file with the same name as the control in the MainPage.xaml.

    You do not need to implement it, because the autogenerated XAML code-behind provides the implemention for you. For more details about it, you can refer to this part.

    Then, you could define a Current property of the MainPage, and access the control in another cpp file using the Current property. For example:

    MainPage.idl:

    runtimeclass MainPage : Windows.UI.Xaml.Controls.Page  
    {  
        MainPage();  
    
        static MainPage Current{ get; };  
        Windows.UI.Xaml.Controls.TextBox input1{ get; };  
    }  
    

    MainPage.h

        static BlankApp1::MainPage Current();  
    
    private:  
        static BlankApp1::MainPage current;  
    

    MainPage.cpp

    BlankApp1::MainPage MainPage::current{ nullptr };  
    
    MainPage::MainPage()  
    {  
        InitializeComponent();  
        MainPage::current = *this;  
    }  
    

    Other page.cpp:

    Windows::UI::Xaml::Controls::TextBox tb = MainPage::Current().input1();  
    
    0 comments No comments