Sunday 6 July 2008

Selecting the Detail Level to View at Runtime in WPF - An even better way!

Regarding my previous post Josh rightly commented that this technique could lead to lots of extra visuals being created that are never displayed, which for large data loads is not desirable and definitely a waste of resources. Josh also made a number of other salient points which are worth reading.

Well it was upon reading this comment that it struck me that there was in fact no need to be creating (and hiding lots of visuals) when they are not used! We simply need a SINGLE content presnter, and just change the template of that with a trigger, like so:

  <DataTemplate x:Key="SelectorTemplate">
    <Grid>
      <ContentPresenter x:Name="proxyDataPresenter" Content="{Binding}" />
    </Grid>
    <DataTemplate.Triggers>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="1">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource LowTemplate}" />
      </DataTrigger>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="2">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource MediumTemplate}" />
      </DataTrigger>
      <DataTrigger Binding="{Binding ElementName=detailLevelSlider, Path=Value}" Value="3">
        <Setter TargetName="proxyDataPresenter" Property="ContentTemplate" 
                Value="{StaticResource HighTemplate}" />
      </DataTrigger>
    </DataTemplate.Triggers>
  </DataTemplate>

The simplicity baffles me and it really works a treat... again this kind of thing just makes me appreciate the sheer power of WPF and it's declarative style of programming.

No comments: