Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't create new view each time with DataTemplate/DataType

I have something like this:

<Window>
    <Window.Resources>
       <DataTemplate DataType="{x:Type local:VM1}">
          <!-- View 1 Here -->
       </DataTemplate>

       <DataTemplate DataType="{x:Type local:VM2}">
          <!-- View 2 here -->
       </DataTemplate>
    <Window.Resources>

    <ContentPresenter Content="{Binding}"/>
</Window>

This will automatically swap out the view as I bind different viewmodels, which is very handy.

However, I have one view with a tabcontrol and many subviews. Each subview has several visual parts that are configured by a custom xml file (complex business case). Each time this view is created, the xml file is parsed which causes a small (1-2 second) delay. It's enough of a delay to be annoying and make the UI feel sluggish.

Is there a way to use the DataTemplate pattern without destroying and recreating the view each time a viewmodel is bound? I'd rather not change the viewmodel if possible.

like image 833
ConditionRacer Avatar asked Nov 02 '22 01:11

ConditionRacer


1 Answers

For this case the easiest solution is to have the two views always there and change which one is visible. You can use a converter to change the visibility based on the type of the data context

<View1 Visibility="{Binding Converter={StaticResource TypeToVisibilityConverter, ConverterParameter=VM1}" />
<View2 Visibility="{Binding Converter={StaticResource TypeToVisibilityConverter, ConverterParameter=VM2}" />

And the converter will check if the type matches with the parameter to return Visible, or Collapsed otherwise.

like image 99
robertos Avatar answered Nov 08 '22 08:11

robertos