Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cache the view when using model first approach?

Tags:

mvvm

wpf

In our product, we use MVVM model first approach and it works nicely but with one caveat. When view becomes complex it takes time to create it from the data template. If the view is shown and hidden frequently, it becomes slightly irritating. If using view first, it would be easy enough to cache a view if needed - but when using DataTemplate and model first, we do not have much control of view creation. Anybody solved this problem already without switching to the view first method?

like image 570
Sergey Aldoukhov Avatar asked Oct 06 '10 23:10

Sergey Aldoukhov


2 Answers

Works beautifully if using the @blindmeis idea.

The overall recipe:

Create a ContentControl or UserControl named ViewCache:

public partial class ViewCache
{
    public ViewCache()
    {
        InitializeComponent();
        Unloaded += ViewCache_Unloaded;
    }

    void ViewCache_Unloaded(object sender, RoutedEventArgs e)
    {
        Content = null;
    }

    private Type _contentType;
    public Type ContentType
    {
        get { return _contentType; }
        set
        {
            _contentType = value;
            Content = ViewFactory.View(value);  // use you favorite factory
        }
    }
}

In the DataTemplate, use the ViewCache, pass the type of the real view you want to use:

<Window.Resources>
    <DataTemplate DataType="{x:Type TestViewCache:Foo}">
        <TestViewCache:ViewCache ContentType="{x:Type TestViewCache:View }"/>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ContentPresenter Height="200" Width="300"
        Content="{Binding ViewModel}"/>
    <Button Content="Set VM" Click="SetVMClick"/>
    <Button Content="UnSet VM" Click="UnSetVMClick"/>        
</StackPanel>
like image 87
Sergey Aldoukhov Avatar answered Oct 16 '22 11:10

Sergey Aldoukhov


with viewmodel first approach i think you have no chance to "cache" the view. so you may consider to use view first and a viewmodel locator for the heavyweight datatemplates workflows. here is a solution when using datatemplates with lists.

but maybe there is any solution with overriding the wpf datatemplate mechanism?

edit: what if you create just a "markerview" for your viewmodel, so wpf datatemplate can find it. and then within this marker view you create/rehydrate the real view? something like an view service locator?

like image 3
blindmeis Avatar answered Oct 16 '22 12:10

blindmeis