BlackCat
BlackCat

Reputation: 521

How can I get a DateTime value with Bindings? (WPF-MVVM)

I would like something like this:

<DatePicker SelectedDate="{Binding StartDate}" />

Is there any control or easy solution for this? (I use MVVM.)

Upvotes: 6

Views: 12203

Answers (2)

kmatyaszek
kmatyaszek

Reputation: 19296

In this case you must have only property StartDate in ViewModel and it will be working.

And when you change date in the DatePicker, it will be automatically reflected in the property StartDate in ViewModel class.

Simple ViewModel:

class MainViewModel : INotifyPropertyChanged
    {
        private DateTime _startDate = DateTime.Now;
        public DateTime StartDate
        {
            get { return _startDate; }
            set { _startDate = value; OnPropertyChanged("StartDate");  }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(name));
        }
    }

Simple View:

<Window x:Class="SimpleBinding.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" mc:Ignorable="d" 
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>    
        <DatePicker SelectedDate="{Binding StartDate}" />        
    </StackPanel>
</Window>

Code-behind:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();         
            this.DataContext = new MainViewModel();
        }        
    }

Upvotes: 15

Kent Boogaart
Kent Boogaart

Reputation: 178780

See the WPF Toolkit (note: CodePlex is down/slow at the time of writing).

Upvotes: 1

Related Questions