Page 1 of 1

VM instance bound to a UI element is not destroyed even after the bind target is nulled.

Posted: 13 Jun 2019, 10:07
by nikobarli
So we have a code like this

xaml
        <Grid>
            <ContentControl Content="{Binding CurrentItem}" />
        </Grid>
C++
class ItemVM : public BaseComponent, public INotifyPropertyChanged
{
    ...
}

class BindingCollectionVM : public BaseComponent, public INotifyPropertyChanged
{
public:
    Ptr<ItemVM> m_item = MakePtr<ItemVM>(); // create ItemVM here

    void ButtonCmd() {
        m_item.Reset();  // Clear the item when a button is clicked
        _propertyChanged(this, NSS(CurrentItem));
    }

    NS_IMPLEMENT_INLINE_REFLECTION(BindingCollectionVM, BaseComponent)
    {
        ...
        NsProp("CurrentItem", &BindingCollectionVM::m_item );
    }
    
We expect that when the ButtonCmd is fired, m_item is reset, then the ItemVM instance we created will be destroyed. However, it seems that the FrameworkElement still hold the reference preventing the destruction.

(as for the appearance, the ItemVM is correctly disappeared from the UI after the reset)

If for example, we create another instance of ItemVM and assign it to m_item, then the previous instance is correctly destroyed.
    void ButtonCmd() {
        m_item = MakePtr<ItemVM>();
        _propertyChanged(this, NSS(CurrentItem));
    }

Re: VM instance bound to a UI element is not destroyed even after the bind target is nulled.

Posted: 17 Jun 2019, 18:50
by sfernandez
Hello,

I've seen that DataContext value is not reset when ContentPresenter.Content gets updated and is keeping alive the old value until the next layout pass occurs. This is something we need to fix, because in that same situation WPF correctly resets the DataContext.

I also verified it doesn't matter if you reset the item or create a new one, the old item always stays alive, the problem lies in ContentPresenter.DataContext property.

Could you please open this issue in the bugtracker, we will fix it as soon as possible.

Re: VM instance bound to a UI element is not destroyed even after the bind target is nulled.

Posted: 18 Jun 2019, 07:44
by nikobarli

Re: VM instance bound to a UI element is not destroyed even after the bind target is nulled.

Posted: 19 Jun 2019, 19:17
by sfernandez
Thanks for the report.