Share via

WinUI3 : Managing lifecycle of widget in c++

Harshithraj1871 1,756 Reputation points
2023-09-26T12:42:03.1466667+00:00

Hi,

I'm working on WinUI3 Desktop app in c++. I'm not using XAML in any part of my code. All the widget creation happens programmatically in c++.

After I create a widget ill store that widget in this IObservableMap

IObservableMap<int, UIElement> gIdMap = single_threaded_observable_map<int, UIElement>();

Like this

void  CreateText ()
{
	StackPanel parent = GetTopContainer ();  // return WinUI3 StackPanel element, which was already visible on screen

	TextBox text;

	text.Text(L"Samnple);

	parent.Childern().Append(text);

    gIdMap.Insert(gNumericID, text.as<UIElement>());

}

Later when I remove the TextBox from parent StackPanel with StackPanel.Children().RemoveAt(index), the TextBox reference in gIdMap will still be there. i,e that wont get destructed

I can understand as everything here is smart pointer, object wont be destructed till the reference count is 0.

My doubt is, how will I clear the TextBox object stored in gIdMap (IObservableMap). Will gIdMap.Remove() clear the memory allocated for the TextBox , Will the TextBox be distructed?

Thank you

Windows development | Windows App SDK
0 comments No comments
{count} votes

Answer accepted by question author
  1. Xiaopo Yang - MSFT 12,736 Reputation points Microsoft External Staff
    2023-09-27T01:38:59.7933333+00:00

    Yes, It will. I have tested and also see WinUI-Gallery.

        MainWindow::MainWindow()
            :m_bookSkus(winrt::single_threaded_observable_vector<IInspectable>())
           //, gIdMap(single_threaded_observable_map<int, Microsoft::UI::Xaml::IUIElement>())
           , gIdMap(single_threaded_observable_map<int, IInspectable>())
        {
            InitializeComponent();
            App1::BookSku p = make<winrt::App1::implementation::BookSku>();
            gIdMap.Insert(1, p);
        }
    
        void MainWindow::myButton_Click(IInspectable const& a, RoutedEventArgs const&)
        {
            myButton().Content(box_value(L"Clicked"));
            gIdMap.Remove(1);
    	}
    

    GIF 9-27-2023 9-36-18 AM


0 additional answers

Sort by: Most helpful

Your answer

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