DatePiker Help

Eduardo Gomez 3,416 Reputation points
2023-04-01T20:37:02.0233333+00:00

I have a Model, with a datetime name DateOfBirth.

    public class LocalUser : ObservableObject {

        private string? firstName;
        private string? lastName;
        private string? password;
        private string? confirm;
        private string? country;
        private string? id;
        private string? email;
        private string? username;
        private string? city;
        private bool hasPaid;
        private bool isActive;
        private int age;
        private DateTime dateOfBirth = new DateTime(); // this is the one
        private DateTime suscriptionStart;
        private DateTime suscriptionEnd;
        readonly CultureInfo culture = CultureInfo.CurrentCulture;

        public LocalUser() {
        }

I am using this is my view model

 public class SignUpLoginWondowViewModel {

        #region Objects that are bindiable to the UI
        public bool isBusy { get; set; } = false;

        public LocalUser User { get; set; }
        public Visibility RegisterVis { get; set; }

        public Visibility LoginVis { get; set; }

        public Visibility isButtonVisible { get; set; }

        #endregion

        #region Command (These are the same as Clicks)
        public AsyncCommand RegisterCommand { get; set; }

        public AsyncCommand LoginCommand { get; set; }

        public Command SwitchViewsCommand { get; set; }
        #endregion

        #region Firebase configuration
        private readonly FirebaseAuthConfig Config;

        private readonly FirebaseAuthService AuthService;

        private readonly FirebaseServices FirebaseServices;
       

and my view is


            <DatePicker
                Margin="0,10,0,0"
                ui:ControlHelper.CornerRadius="10"
                ui:ControlHelper.PlaceholderText="{x:Static res:Lang.Birth}"
                FlowDirection="RightToLeft"
                FocusVisualStyle="{x:Null}"
                SelectedDate="{Binding User.DateOfBirth, UpdateSourceTrigger=PropertyChanged}" />

the problem is that the default value for the datepiker is

     1/1/0001

and if I delete that i can see the placehoilder

but I want the placeholder to be the default value

User's image

Also hen I display the calendar, I can pick dates from January 001

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,686 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 41,331 Reputation points Microsoft Vendor
    2023-04-03T08:03:30.71+00:00

    Hi,@ Eduardo Gomez . You could try to refer to the following code if you want to display the watermark at the beginning and then display the selected date when the user selects the calendar.

    Model :

     private DateTime dateOfBirth ; 
            public DateTime DateOfBirth
            
            {
                get => dateOfBirth;
                set => SetProperty( ref dateOfBirth, value);
            }
    

    ViewModel:

    
       User= new LocalUser() { DateOfBirth=DateTime.Now   };
    
    

    Method A:

     <DatePicker  x:Name="dp" 
                    Margin="0,10,0,0" Loaded="DatePicker_Loaded"
                  
                    FlowDirection="RightToLeft"
                    FocusVisualStyle="{x:Null}"
                    SelectedDate="{Binding User.DateOfBirth, UpdateSourceTrigger=PropertyChanged,Mode=OneWayToSource}"  Validation.ErrorTemplate="{x:Null}"/>
    
    

    Codebehind:

      private void DatePicker_Loaded(object sender, RoutedEventArgs e)
            {
                DatePicker datePicker = sender as DatePicker;
                if (datePicker != null)
                {
                    System.Windows.Controls.Primitives.DatePickerTextBox datePickerTextBox = FindVisualChild<System.Windows.Controls.Primitives.DatePickerTextBox>(datePicker);
                    if (datePickerTextBox != null)
                    {
    
                        ContentControl watermark = datePickerTextBox.Template.FindName("PART_Watermark", datePickerTextBox) as ContentControl;
                        if (watermark != null)
                        {
                            watermark.Content = "Fecha de Nacimiento";
                            //or set it some value here...
                        }
                    }
                }
            }
    
            private T FindVisualChild<T>(DependencyObject depencencyObject) where T : DependencyObject
            {
                if (depencencyObject != null)
                {
                    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depencencyObject); ++i)
                    {
                        DependencyObject child = VisualTreeHelper.GetChild(depencencyObject, i);
                        T result = (child as T) ?? FindVisualChild<T>(child);
                        if (result != null)
                            return result;
                    }
                }
    
                return null;
            }
    

    Method B:

     <Window.DataContext>
            <local:SignUpLoginWondowViewModel/>
        </Window.DataContext>
        <Window.Resources>
          
    
            <Style TargetType="{x:Type DatePickerTextBox}">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" />
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
                <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
                <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="DatePickerTextBox">
                            <Grid>
                                <Grid.Resources>
                                    <SolidColorBrush x:Key="WatermarkBrush" Color="#FFAAAAAA"/>
                                    
                                </Grid.Resources>
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup Name="CommonStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0" />
                                            <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.1" />
                                        </VisualStateGroup.Transitions>
                                        <VisualState Name="Normal" />
                                        <VisualState Name="MouseOver">
                                            <Storyboard>
                                                <ColorAnimation Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" To="#FF99C1E2" Duration="0"/>
                                                <ColorAnimation Storyboard.TargetName="watermark_decorator" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" To="#FF99C1E2" Duration="0"/>
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup Name="WatermarkStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0" />
                                        </VisualStateGroup.Transitions>
                                        <VisualState Name="Unwatermarked" />
                                        <VisualState Name="Watermarked">
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Opacity" To="0" Duration="0" />
                                                <DoubleAnimation Storyboard.TargetName="PART_Watermark" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                    <VisualStateGroup Name="FocusStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0" />
                                        </VisualStateGroup.Transitions>
                                        <VisualState Name="Unfocused" />
                                        <VisualState Name="Focused">
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="FocusVisual" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                            </Storyboard>
                                        </VisualState>
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
    
    
                                <Border x:Name="Border" 
                                Background="{TemplateBinding Background}" 
                                BorderBrush="{TemplateBinding BorderBrush}" 
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}"
                                CornerRadius="1" 
                                Opacity="1">
                                    <Grid x:Name="WatermarkContent"
                                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                                        <Border x:Name="ContentElement" BorderThickness="1">
                                            <Border.BorderBrush>
                                                <SolidColorBrush Color="#FFFFFFFF"/>
                                            </Border.BorderBrush>
                                        </Border>
                                        <Border x:Name="watermark_decorator" BorderThickness="1">
                                            <Border.BorderBrush>
                                                <SolidColorBrush Color="#FFFFFFFF"/>
                                            </Border.BorderBrush>
                                            <ContentControl x:Name="PART_Watermark"
                                                        Opacity="0"
                                                        Focusable="False"
                                                        IsHitTestVisible="False"
                                                        Padding="2">
                                                <ContentControl.Template>
                                                    <ControlTemplate>
                                                        <TextBlock Text="Fecha de Nacimiento"/>
                                                    </ControlTemplate>
                                                </ContentControl.Template>
                                            </ContentControl>
                                        </Border>
                                        <ScrollViewer x:Name="PART_ContentHost" 
                                              Margin="0"
                                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
                                        <Border x:Name="FocusVisual" BorderBrush="#FF45D6FA" CornerRadius="1" Opacity="0" IsHitTestVisible="False"/>
                                    </Grid>
                                </Border>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Window.Resources>
        <Grid>
            <DatePicker  x:Name="dp" 
                    Margin="0,10,0,0"
                
                    FlowDirection="RightToLeft"
                    FocusVisualStyle="{x:Null}"
                    SelectedDate="{Binding User.DateOfBirth, UpdateSourceTrigger=PropertyChanged,Mode=OneWayToSource}"  Validation.ErrorTemplate="{x:Null}" />
        </Grid>
    
    
    

    The result:

    7

    -

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful