How to get in DatePicker the selected date in ObservableCollection

Sarah 186 Reputation points
2022-02-10T04:55:49.747+00:00

Hi, I use the DatePicker for entering birthday but after saving I don't get the selected date in the viewlist. Instead I get another date and time.
It should be saved today's date(default displayed) if no other date is selected in DatePicker.
Can someone tell me why this does not work?

Thanks
Sarah

MainWindow

<Window x:Class="MyContacts.MainWindow"
        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:local="clr-namespace:MyContacts"
        mc:Ignorable="d"
        Title="My Contcats" Height="450" Width="500">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="400"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>

        <ListView Grid.Column="0" x:Name="ContactListView" ItemsSource="{Binding View}" Margin="5">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Border BorderBrush="CadetBlue" BorderThickness="0,2,0,2" Width="375" Padding="5">
                        <StackPanel>
                            <TextBlock Text="{Binding Firstname}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Lastname}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Birthday}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Address}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Email}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Phone}" TextWrapping="Wrap"/>
                            <TextBlock Text="{Binding Specialty}" TextWrapping="Wrap"/>
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" Margin="0,0,0,0">
            <Button Height="30" Width="60" Content="Add" Margin="10" Click="Add_Click"/>
            <Button Height="30" Width="60" Content="Edit" Margin="10" Click="Edit_Click"/>
            <Button Height="30" Width="60" Content="Remove" Margin="10" Click="Remove_Click"/>
        </StackPanel>
    </Grid>
</Window>

Code

using System.Windows;


namespace MyContacts
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = ViewModel.Instance; //Why do I need this ?
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            var addContactWindow = new AddContactWindow();
            ContactDetail contactData = new ContactDetail();
            addContactWindow.DataContext = contactData;
            addContactWindow.ShowDialog();
            if (addContactWindow.DataContext != null)
            {
                ViewModel.Instance.ContactDetails.Add(contactData);
                ViewModel.Instance.OnPropertyChanged("View");
            }
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            if (ContactListView.SelectedItem != null)
            {
                ContactDetail contactData = ContactListView.SelectedItem as ContactDetail;
                if (contactData == null)
                {
                    return;
                }
                else
                {
                    var addContactWindow = new AddContactWindow();
                    contactData.Cache();
                    addContactWindow.DataContext = contactData;
                    addContactWindow.ShowDialog();
                    if (addContactWindow.DataContext == null)
                    {
                        contactData.Restore();
                    }
                }
            }
        }

        private void Remove_Click(object sender, RoutedEventArgs e)
        {
            if (ContactListView.SelectedItem != null)
            {
                MyContacts.ViewModel.Instance.ContactDetails.Remove(ContactListView.SelectedItem as ContactDetail);
            }
        }
    }
}

Add Contact Window

<Window x:Class="MyContacts.AddContactWindow"
        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:local="clr-namespace:MyContacts"
        mc:Ignorable="d"
        Title="Contact" Height="350" Width="400">
    <Grid>
        <StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,10,0,10">
                <Label Content="Firstname:" Width="120" />
                <TextBox Height="25" Width="230" Margin="0,0,5,0" Text="{Binding Path=Firstname, UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Lastname:" Width="120" />
                <TextBox Height="25" Width="230" Margin="0,0,5,0" Text="{Binding Path=Lastname, UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Birthday:" Width="120" />
                <DatePicker x:Name="Birthday" Text="{Binding Path=Birthday, UpdateSourceTrigger=PropertyChanged}" SelectedDateFormat="Short"  Height="25" Width="230" FirstDayOfWeek="Monday" IsTodayHighlighted="True" SelectedDate="{Binding DisplayDate.Today, ElementName=Birthday, Mode=OneWay}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Address:" Width="120" />
                <TextBox Height="25" Width="230" Margin="0,0,5,0" Text="{Binding Path=Address, UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Phone:" Width="120" />
                <TextBox Height="25" Width="230" Margin="0,0,5,0" Text="{Binding Path=Phone, UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Email:" Width="120" />
                <TextBox Height="25" Width="230" Margin="0,0,5,0" Text="{Binding Path=Email, UpdateSourceTrigger=PropertyChanged}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">
                <Label Content="Specialty:" Width="120" />
                <ComboBox x:Name="Specialty" Text="{Binding Path=Specialty, UpdateSourceTrigger=PropertyChanged}" Height="25" Width="230" Margin="0,0,5,0" >
                    <ComboBoxItem Content="A"/>
                    <ComboBoxItem Content="B"/>
                    <ComboBoxItem Content="C"/>
                </ComboBox>
            </StackPanel>
        </StackPanel>

        <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="10,0,10,10">
            <Button Height="30" Width="70" Content="Close" Margin="10,0,0,0" Click="Close_Click" />
            <Button Height="30" Width="70" Content="Save" Margin="10,0,0,0" Click="Save_Click" />
        </StackPanel>
    </Grid>
</Window>

Code

using System.Windows;

namespace MyContacts
{
    /// <summary>
    /// Interaktionslogik für Contact.xaml
    /// </summary>
    public partial class AddContactWindow : Window
    {
        public AddContactWindow()
        {
            InitializeComponent();
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = null;
            Close();
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

Class ContactDetail

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Data;

namespace MyContacts
{
    public class ContactDetail : INotifyPropertyChanged
    {
        private string _Firstname;
        private string _Lastname;
        private string _Address;
        private string _Phone;
        private string _Email;
        private DateTime _Birthday;
        private string _Specialty;


        public ContactDetail() { }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = "") =>
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));


        #region Properties Getters and Setters

        public string Firstname
        {
            get { return _Firstname; }
            set { _Firstname = value; OnPropertyChanged(); }
        }

        public string Lastname
        {
            get { return _Lastname; }
            set { _Lastname = value; OnPropertyChanged(); }
        }

        public string Address
        {
            get { return _Address; }
            set { _Address = value; OnPropertyChanged(); }
        }

        public string Phone
        {
            get { return _Phone; }
            set { _Phone = value; OnPropertyChanged(); }
        }

        public string Email
        {
            get { return _Email; }
            set { _Email = value; OnPropertyChanged(); }
        }

        public DateTime Birthday
        {
            get { return _Birthday; }
            set { _Birthday = value; OnPropertyChanged(); }
        }

        public string Specialty
        {
            get { return _Specialty; }
            set { _Specialty = value; OnPropertyChanged(); }
        }

        #endregion Properties Getters and Setters

        private string _Firstname_Cache;
        private string _Lastname_Cache;
        private string _Address_Cache;
        private string _Phone_Cache;
        private string _Email_Cache;
        private DateTime _Birthday_Cache;
        private string _Specialty_Cache;

        public void Cache()
        {
            _Firstname_Cache = _Firstname;
            _Lastname_Cache = _Lastname;
            _Address_Cache = _Address;
            _Phone_Cache = _Phone;
            _Email_Cache = _Email;
            _Birthday_Cache = _Birthday;
            _Specialty_Cache = _Specialty;
        }
        public void Restore()
        {
            Firstname = _Firstname_Cache;
            Lastname = _Lastname_Cache;
            Address = _Address_Cache;
            Phone = _Phone_Cache;
            Email = _Email_Cache;
            Birthday = _Birthday_Cache;
            Specialty = _Specialty_Cache;
        }
    }

    public class ViewModel : INotifyPropertyChanged
    {
        private static ViewModel _instance;
        static ViewModel()
        {
            _instance = new ViewModel();
            _instance.ContactDetails = new ObservableCollection<ContactDetail>();
            _instance.cvs.Source = _instance.ContactDetails;
        }

        public static ViewModel Instance { get => _instance; }

        public ICollectionView View { get => cvs.View; }
        private CollectionViewSource cvs = new CollectionViewSource();

        public ObservableCollection<ContactDetail>? ContactDetails { get; set; }


        public event PropertyChangedEventHandler? PropertyChanged;
        internal void OnPropertyChanged([CallerMemberName] string name = "") =>
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
Developer technologies Windows Presentation Foundation
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2022-02-10T07:12:35.957+00:00

    You could modify DatePicker in AddContactWindow.xaml as follows:

    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,10">  
                    <Label Content="Birthday:" Width="120" />  
                   <DatePicker x:Name="Birthday"  SelectedDateFormat="Short"  Height="25" Width="230" FirstDayOfWeek="Monday" IsTodayHighlighted="True"    
                            SelectedDate="{Binding Birthday ,  UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>  
                </StackPanel>  
    

    Initialize _Birthday in the ContactDetail class as follows:

     private DateTime _Birthday = DateTime.Now;  
    

    Modify the TextBlock that displays Birthday in MainWindow:

      <TextBlock Text="{Binding Birthday , StringFormat={}{0:MM/dd/yyyy} }"  TextWrapping="Wrap"/>  
    

    The result:
    173075-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.