xamlwinui-3winuiwindows-app-sdkwinui-xaml

How to dispose the events and properties when creating custom controls in WinUI 3?


I have created a custom control in winui3 and in OnApplyTemplate() i have subscribed for few events. How to unsubscribe these events? . I have tried it in unloaded event but unloaded event is called initially when the control is created which is causing the events to dispose unnecessarily. How to fix this?

protected override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    
    toggleButton = GetTemplateChild("PART_ToggleButton") as Button;
    popup = GetTemplateChild("PART_Popup") as Popup;
    listView = GetTemplateChild("PART_ListView") as ListView;
    popupGrid = GetTemplateChild("PART_PopupGrid") as Grid;
    textBlock = GetTemplateChild("PART_ContentTextBlock") as TextBlock;
    if (popup != null)
    {
        popup.Closed += Popup_Closed;
        popup.Opened += Popup_Opened;
    }
}

Solution

  • This is how I usually do in my custom controls.

    private Popup? PART_Popup { get; set; }
    
    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    
        if (popup is not null)
        {
            popup.Closed -= Popup_Closed;
            popup.Opened -= Popup_Opened;  
        }
    
        if (GetTemplateChild(nameof(PART_Popup)) is Popup popup)
        {
            popup.Closed += Popup_Closed;
            popup.Opened += Popup_Opened;
        }
    }