How to change Silverlight DatePicker watermark

When you add DatePicker control you get “<m/d/yyyy>” watermark by default. There is no direct property available in Silverlight DatePicker control to change its watermark.

DatePickerWatermark.jpg

But you can change watermark by overriding OnApplyTemplate method of DatePicker control class. To do this Add new class file with the name “CustomDatePicker.cs” and derive it from DatePicker class. The DatePicker control has template of type DatePickerTextBox which has Watermark property, you can get the template using GetTemplateChild method and set the watermark as per your requirement.

 

public class CustomDatePicker : System.Windows.Controls.DatePicker

{

public override void OnApplyTemplate()

        {

            base.OnApplyTemplate();

            DatePickerTextBox dtTextBox = this.GetTemplateChild("TextBox") as DatePickerTextBox;

            dtTextBox.Watermark = "dd/mm/yyyy";

        }

}

Once custom control is created, add custom DatePicker control in MainPage.xaml. Remember before adding control you have to add xml namespace.

 

<UserControl x:Class="DatePickerWatermark.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:custDt="clr-namespace:DatePickerWatermark"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White" Margin="20,20,20,20">

        <StackPanel>

            <custDt:CustomDatePicker Width="110" Height="22"/>

        </StackPanel>

    </Grid>

</UserControl>


Now run the application

DatePickerCustomWatermark.jpg

You can see the watermark is changed to “mm/dd/yyyy”.