WPF- TimePicker Binding to set date and time at runtime-Collection of common programming errors
In my Wpf app, I’ve two TimePickers. I’ve used binding for them but their time is not updating. I also want to set selected date for these TimePickers.I tried to bind it as below. But, it won’t work. Actual problem here is TimePickers are inside DataTemplate.
Here is xaml:
Binding with properits in C#:
private DateTime _dateTime1;
public DateTime StartValue
{
get
{
return _dateTime1;
}
set
{
_dateTime1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
OnPropertyChanged("StartValue");
}
}
private DateTime _dateTime2;
public DateTime EndValue
{
get
{
return _dateTime2;
}
set
{
_dateTime2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
OnPropertyChanged("EndValue");
}
}
protected virtual void OnPropertyChanged(String time)
{
if (System.String.IsNullOrEmpty(time))
{
return;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(time));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
Please suggest some ideas?
-
You are trying to set your values in your property setters which will never get called so the property value will never be set (and therefore never notified, and the TimePicker will never update).
Why not try setting the properties in the constructor of your ViewModel. I’m not sure what your ViewModel is called but here goes:
public class MyViewModel : INotifyPropertyChanged { public MyViewModel() { StartValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); EndValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); } private DateTime _dateTime1; public DateTime StartValue { get { return _dateTime1; } set { if (_dateTime1.Equals(value)) return; _dateTime1 = value; OnPropertyChanged("StartValue"); } } private DateTime _dateTime2; public DateTime EndValue { get { return _dateTime2; } set { if (_dateTime2.Equals(value)) return; _dateTime2 = value; OnPropertyChanged("EndValue"); } } protected virtual void OnPropertyChanged(String time) { if (System.String.IsNullOrEmpty(time)) { return; } if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(time)); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion }
This will ensure the PropertyChanged events are fired for both properties and as long as your binding is correct you will see the values update.