I’m making a calendar usercontrol. It’s got a start date and an end date as properties like so
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
so that I can call the Usercontrol like this
<Local:CalendarControl StartDate="7/1/2013" EndDate="8/11/2013">
</Local:CalendarControl>
Now inside the usercontrol, I need to calculate the weeknumbers for and dates between the start and end date. For this I naturally need to use the selected start date and end date. But by the time the bindings are calculated, the properties have not yet been set.
So the properties that are being bound looks like this:
public List<DateTime> Dates
{
get
{
var dateTimes = new List<DateTime>();
for (var currentDate = StartDate; currentDate <= EndDate; currentDate = currentDate.AddDays(1))
dateTimes.Add(currentDate);
return dateTimes;
}
}
public List<int> Weeks
{
get
{
var weeks = new List<int>();
if (DateTimeFormatInfo.CurrentInfo != null)
{
var cal = DateTimeFormatInfo.CurrentInfo.Calendar;
foreach (var dateTime in Dates)
{
var weekNum = cal.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
if (weeks.All(f => f != weekNum))
{
weeks.Add(weekNum);
}
}
}
return weeks;
}
}
And in the XAML its the DATES and WEEKS propeties that are bound. But they depend on the StartDate and EndDate being set first.
How can I make sure that the properties are set when they are bound. Or is there a better way of doing this?
Change your StartDate and EndDate Properties to DependencyProperties and in their Property Changed Callback raise the Property Changed event for the Dates and Weeks:
How To Raise Property Changed events on a Dependency Property?