How can I create and modify Xaml UI elements in .cpp files (C++/WinRT)?

0

I need to make a Xaml UI element in a .cpp file my C++/WinRT project (in also Win32 Desktop and WinUI3, not UWP), but I'm having a threading error.

WinRT originate error - 0x8001010E : 'The application called an interface that was marshalled for a different thread.'

I think one thing for sure is that I need to get on the UI thread somehow. Through looking at a lot of various search engine answers and Stack Overflow answers, I have looked into Hosting a custom UWP control in a C++ Win32 app. But using Xaml Islands involves extensive additions to my current project and I'm still not sure after some lookups whether a Xaml control is synonymous to UWP control. Trying to see if this big leap into Xaml Islands is truly the only way to do this, I have also looked into Programming with Threading Affinity in Mind as this also seems to be able to directly create and modify Xaml UI elements. However, the example here uses a passed in Xaml UI element rather than creating one from scratch.

Here is the code snippet that causes the error message on top, although I'm not sure it's helpful since it is very bare and I am aware it's not on the UI thread.

// the local pch.h file contains various winrt/[UI Xaml] header files.
#include "pch.h"

#include <winrt/Windows.UI.Xaml.Controls.h>
#include "MyProjViewModel.h"
#include "MyProjViewModel.g.cpp"

using namespace winrt;

namespace winrt::MyProj::implementation
{
    MyProjViewModel::MyProjViewModel() : m_myProjContent(winrt::make<MyProj::implementation::MyProjContent>())
    {
        // the line that causes the error
        winrt::Windows::UI::Xaml::Controls::NavigationViewItem homeItem;
        // do things with homeItem
    }

    ...
}

P.S. This is my first Stack Overflow question ever, please let me know about any improvements I could make in crafting a clear question with enough info :)

Edit: added comment to line that causes error

c++
xaml
winrt-xaml
c++-winrt
winui-3
asked on Stack Overflow Oct 2, 2020 by hello-there

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0