开发者

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

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?


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>


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜