I have a UserControl (MainView) which needs to display another UserControl inside itself. Depending on some condition, it will display either AView or BView (they both appear on the same place in MainView). I am using ViewModel first approach, so Views are generated through data templates:
public class AView : UserControl { }
public class BView : UserControl { }
public class AViewModel : ViewModelBase { }
public class BViewModel : ViewModelBase { }
From the resource usage point, is there a difference between these two approaches:
1) Having one ContentControl
<ContentControl Content="{Binding SomeViewModel}" />
private ViewModelBase _someViewModel;
public ViewModelBase SomeViewModel
{
get {return _someViewModel;}
set
{
if (!ReferenceEquals(_someViewModel, value))
{
_someViewModel = value;
RaisePropertyChange(SomeViewModel);
}
}
}
This way I can choose which ViewModel (AViewModel or BViewModel) will I set to SomeViewModel, and DataTemplates will choose the appropriate view to display.
2) Placing two ContentControls, and control Visibility of each of them (only one is visible at a time).
<ContentControl Content="{Binding AViewModel}"
Visibility="{Binding SomeCondition}" />
<ContentControl Content="{Binding BViewModel}"
Visibility="{Binding NotSomeCondition}" />
So, from the point of resource management, will switching between these two views behave any differently, or in both cases only one view will reside in memory at a given time?
WPF unloads objects which are not visible so at any given time only one of your Views will be loaded for both methods, however your 2nd method will create two ContentControl's in the UI, while the first only creates one.
In addition, there is the added (miniscule) overhead of evaluating the
Visibility
anytime your Content view model changes. TheDataTemplate
will be evaluated either way since you are setting theContent
to aViewModel
, and WPF will have to determine how to draw that ViewModel by looking for theDataTemplate
Personally I prefer the first version. It's easier to maintain and manage, especially when you have more than just 2 views, and only one
ContentControl
exists in the UI at a time