How are objects generated by XAML?
I am developing a WPF application using MVVM pattern and Entity Framework. I wrote a class that contains a list of lists that are populated from a database. Lists are used to populate ComboBoxes
other `ItemsControls.
Here's the basic structure:
namespace MiniManager.ViewModel
{
public class LookupLists
{
public LookupLists()
{
using (var db = new ModelContext())
{
Supervisors = db.Users.ToList().Where(u => u.Supervisor);
// More lists...
}
}
public IEnumerable<User> Supervisors { get; set; }
// More lists...
}
}
I am using class in view like this:
<UserControl.Resources>
<lists:LookupLists x:Key="LookupLists"/>
</UserControl.Resources>
When I need to use it in a control, I bind to a property in a resource:
<ComboBox ItemsSource="{Binding Source={StaticResource LookupLists},
Path=Supervisors}"/>
My question is:
- How long does the object last
LookupLists
?- While the user interface is active?
- Is a new instance created
LookupLists
(and thus the database queried) every time it needs to?
source to share
Depending on where and how you declare your resource:
Where:
-
if you declare it as a local resource
UserControl
then it will basically refer to that object and will continue as long as the object lasts and the GC does not collect memory -
if you declare it as a global resource in a file
App.xaml
then it will be available for the lifetime of the application
how
-
by default the resources are shared , so only one instance is created and each link is eg. through
StaticResource
, points to the same unique object -
if you declare the resource as
x:Shared="False"
, then each link will cause a new instance to be generated
source to share
Items declared in Resources
are added to a special collection that is a member FrameworkElement
. This way, the collection will run as long as the checkout is done.
If the control is not destroyed, there will be no additional requests (unless you make them).
See MSDN for details on properties Resources
where they are stored .
source to share