I would like something like this:
<DatePicker SelectedDate="{Binding StartDate}" />
Is there any control or easy solution for this? (I use MVVM.)
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();
}
}
See the WPF Toolkit (note: CodePlex is down/slow at the time of writing).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With