Search code examples
c#wpf

how to add a customtext to datepicker text box


i designed a textbox foe date picker but i cant add a custom text inside the textbox before choosing date.i want to add "select a date"


<Grid>
        <DatePicker x:Name="DateGviya" SelectedDate="{Binding CurrentDate}"  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="97,77,0,0">
            <DatePicker.Resources>
                <Style TargetType="{x:Type DatePickerTextBox}">
                    <Setter Property="Control.Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy hh:mm:ss tt', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DatePicker.Resources>
        </DatePicker>
    </Grid>


result is like this: enter image description here


Solution

  • You could use the TargetNullValue property of the binding:

    <DatePicker x:Name="DateGviya" SelectedDate="{Binding CurrentDate}"  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="97,77,0,0">
        <DatePicker.Resources>
            <Style TargetType="{x:Type DatePickerTextBox}">
                <Setter Property="Control.Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBox x:Name="PART_TextBox" 
                                     Text="{Binding Path=SelectedDate, 
                                        StringFormat='dd/MM/yyyy hh:mm:ss tt', 
                                        RelativeSource={RelativeSource AncestorType={x:Type DatePicker}},
                                        TargetNullValue='Select a Date'}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </DatePicker.Resources>
    </DatePicker>