Reputation: 1793
I need to get reference to a Calendar
in a DatePicker
object.
I imagined it to be this easy:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
but there is no Calendar
property in DatePicker
.
Is there any way how to get that reference?
Upvotes: 2
Views: 1925
Reputation: 37
Try this code:
Popup popup = Template.FindName("PART_Popup", this) as Popup;
_calendar = (Calendar)popup.Child;
Upvotes: 0
Reputation: 22702
Try this:
private void Window_ContentRendered(object sender, EventArgs e)
{
// Find the Popup in template
Popup MyPopup = FindChild<Popup>(MyDatePicker, "PART_Popup");
// Get Calendar in child of Popup
Calendar MyCalendar = (Calendar)MyPopup.Child;
// For test
MyCalendar.BlackoutDates.Add(new CalendarDateRange(
new DateTime(2013, 8, 1),
new DateTime(2013, 8, 10)
));
}
Note:
Always use FindChild
only when the control will be fully loaded, otherwise it will not find it and give null. In this case, I put this code in the event ContentRendered
of Window
which says that all the contents of the window successfully load.
Listing of FindChild<>
:
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
if (parent == null)
{
return null;
}
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null) break;
}
else
if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement.Name == childName)
{
foundChild = (T)child;
break;
}
else
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null)
{
break;
}
}
}
else
{
foundChild = (T)child;
break;
}
}
return foundChild;
}
Upvotes: 2