Reputation: 397
An exception is thrown at the declaration of a variable declared as global for the translation unit.
Visual Studio 2017 Community, version 15.9.5, with C++/WinRT extension installed. Project was started from "Blank App (C++/WinRT) template.
I want a variable array, SolidColorBrush myBrushes[2];
, to be used globally in only a single translation unit. It is declared in the namespace of the translation unit.
I have tried fully qualifying the type, labeling the type as static
, and trying it without the array designation.
#include "pch.h"
#include "MainPage.h"
//#include <winrt/Windows.UI.Xaml.Media.h>
using namespace winrt;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
//*************************************************************************************************
namespace winrt::event_Experiment::implementation
{
//*************************************************************************************************
//Windows::UI::Xaml::Media::SolidColorBrush myBrushes[2];
//static SolidColorBrush myBrushes[2];
SolidColorBrush myBrushes[2];
//*************************************************************************************************
MainPage::MainPage()
{
InitializeComponent();
//myBrush.Color(Windows::UI::Colors::Blue());
//myBrush[1].Color(Windows::UI::Colors::Red());
//myStackPanel().Background() = myBrush;
//SolidColorBrush tempBrush = SolidColorBrush(winrt::Windows::UI::Colors::Blue());
//myBrush(tempBrush);
myButton2().Click({ this, &MainPage::ClickHandler2 });
myStackPanel().PointerPressed({ this, &MainPage::spPointerPressed });
//myBrushes[0].Color(Windows::UI::Colors::Blue());
//myBrushes[1].Color(Windows::UI::Colors::Red());
}
The exception thrown is shown in the figure below.
The claim made by Microsoft at the May, 2018 announcement of the update to C++/WinRT is that it is straight C++ 17 which would allow such a declaration.
How can I get this to work? Thanks.
Upvotes: 2
Views: 153
Reputation: 3115
"The claim made by Microsoft at the May, 2018 announcement of the update to C++/WinRT is that it is straight C++ 17 which would allow such a declaration."
C++/WinRT is standard C++17 and as a standard C++ library, a type's constructor may throw an exception indicating that you are using it wrong. In this case the constructor is failing because the SolidColorBrush may only be constructed on a Xaml UI thread. As Raymond pointed out in his comment, you need to ensure that Xaml is initialized before creating Xaml resources. One way to do this is to use the nullptr constructor to defer construction until later. For example:
SolidColorBrush brush{ nullptr };
You can then assign a value to the brush when you are good and ready.
brush = SolidColorBrush(...);
Upvotes: 2