Wednesday, May 12, 2010

Implicitly “degrading” ui controls

If this is valuable then mostly as an idea for now. Current implementation might be too limited and can be further enhanced.

The goal is to hide or disable ui controls if they do not show anything, or whatever they show is missing. Degrades=Hide or Disable.

In WPF terms and in this cut, I’ve made that ui control becomes hidden or disabled automatically if when DataContext becomes null. This implies that host has to be bound to something real, and presence of that real thing implicitly degrades(or not) the host.

Styles from Resources
  1. <Style x:Key="hideStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  2.     <Style.Setters>
  3.       <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Visible}" />
  4.     </Style.Setters>
  5.     <Style.Triggers>
  6.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  7.         <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Hidden}" />
  8.       </DataTrigger>
  9.     </Style.Triggers>
  10.   </Style>
  12.   <Style x:Key="disableButtonIfNull" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
  13.     <Style.Setters>
  14.       <Setter Property="UIElement.IsEnabled" Value="True" />
  15.     </Style.Setters>
  16.     <Style.Triggers>
  17.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  18.         <Setter Property="UIElement.IsEnabled" Value="False" />
  19.       </DataTrigger>
  20.     </Style.Triggers>
  21.   </Style>
  23.   <Style x:Key="disableStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  24.     <Style.Setters>
  25.       <Setter Property="UIElement.IsEnabled" Value="True" />
  26.     </Style.Setters>
  27.     <Style.Triggers>
  28.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  29.         <Setter Property="UIElement.IsEnabled" Value="False" />
  30.       </DataTrigger>
  31.     </Style.Triggers>
  32.   </Style>

Usage Example
  1. <StackPanel DataContext="{Binding ElementName=myList, Path=SelectedItem}"
  2.           VerticalAlignment="Center" Orientation="Horizontal"
  3.           Style="{StaticResource hideStackPanelIfNull}">
  4.     <TextBlock Text="Name:"></TextBlock>
  5.     <TextBlock Text="{Binding Path=Name}"></TextBlock>
  6. </StackPanel>


In this example StackPanel is bound to SelectedItem. If there is nothing in the list, SelectedItem becomes null and that degrades the controls that bear presented here styles, textblocks become disabled or hidden.

Some caveat. Obviously this requires to overwrite your style. It might conflict with your style requirements. In above shown example I am pointing to StackPanels which usually do not need style.


Post a Comment