Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

GC and StaticResources

$
0
0

Hi

Suppose I create may ViewModel like this

<SomeView.Resources><vm:myViewModel x:Key="myViewModelInstance" />
</SomeView.Resources>
Then I use it at some places:
<SomeView
   ...
    DataContext="{StaticResource ResourceKey=myViewModelInstance}"
    ...><SomeView.ItemTemplate><DataTemplate><Button Command="{Binding Source={StaticResource ResourceKey=myViewModelInstance}, Path=SomeButtonCommand}" Content="Go" />
        ...
    ...
...

Shouldn't the instance of the VM get GC'ed / finalized, some short time after the View is unloaded / removed?
Under the precondition that no other references to the VM instance have been established than those of the XAML-DataBindings?

When adding a destructor / finalizer to the VM - which should be called, just before the instance is collected - its confusing to realize, that the VM only seems to get GC'ed when the TopLevel window thus the AppDomain itself unloads, but not when or soon after the View unloads. How can this be?

Does anyone have a good pointer how StaticResources' lifecycles are managed?
Is it a bad idea to instantiate DataContexts as resources?

Thx,
Chris






Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>