Jerry Nixon @Work: Simply change a WPF DatePicker's disabled Style

Jerry Nixon on Windows

Tuesday, July 19, 2011

Simply change a WPF DatePicker's disabled Style

The reality is that the disabled style of a DatePicker in WPF is difficult to read. You COULD restyle the whole freaking thing. Or you could do something simple, like just re-templating the control based on the IsEnabled property.

Like this:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="650" Width="550">
    <Window.Resources>        
        <sys:DateTime x:Key="MyValue">1/1/2000</sys:DateTime>
        <Style TargetType="{x:Type DatePicker}">
            <Style.Triggers>
              <Trigger Property="IsEnabled" Value="false">
                 <Setter Property="Template">
                     <Setter.Value>
                         <ControlTemplate>
                             <Border BorderBrush="Black" BorderThickness="1">
                                 <TextBlock Text="{Binding Path=SelectedDate,
                                 StringFormat={}{0:d},
                                 RelativeSource={RelativeSource TemplatedParent}}"
                                 VerticalAlignment="Center" HorizontalAlignment="Left"
                                 Padding="4,0,0,0" />
                             </Border>
                         </ControlTemplate>
                     </Setter.Value>
                 </Setter>
             </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <DatePicker IsEnabled="False" SelectedDate="{StaticResource MyValue}" 
                Width="100" Height="25" />
</Window>