Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 396
BlackCat Avatar asked Dec 19 '12 19:12

BlackCat


2 Answers

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();
        }        
    }
like image 163
kmatyaszek Avatar answered Nov 12 '22 10:11

kmatyaszek


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

like image 20
Kent Boogaart Avatar answered Nov 12 '22 09:11

Kent Boogaart