Wednesday, May 26, 2010

SelectedItem disables associated Buttons

image

Situation: There is a List, and some buttons that are ought to act on current selected item in the list. But if there are no items or no item is selected then you want these buttons to be disabled.

The idea: Having buttons disabled/enabled implicitly/automatically based on the currently selected item in the list.

Style:
  1. <Style x:Key="disableIfNoListItemSelected" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
  2.   <Style.Setters>
  3.     <Setter Property="UIElement.IsEnabled" Value="True" />
  4.   </Style.Setters>
  5.   <Style.Triggers>
  6.     <DataTrigger Binding="{Binding SelectedIndex}" Value="-1">
  7.       <Setter Property="UIElement.IsEnabled" Value="False" />
  8.     </DataTrigger>
  9.   </Style.Triggers>
  10. </Style>

 

Usage:
  1. <Button Name="cmdShow"
  2.                     DataContext="{Binding ElementName=grdTemplates}"
  3.                     Style="{StaticResource disableIfNoListItemSelected}">
  4.                 </Button>

Notice in the usage, when applying a style to a button, it is required to assign a DataContext of this button to the List that is being watched.

0 comments:

Post a Comment