我需要Calendar
在DatePicker
对象中获取对 a 的引用。
我想这很容易:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
但 中没有Calendar
财产DatePicker
。
有什么办法可以得到那个参考吗?
我需要Calendar
在DatePicker
对象中获取对 a 的引用。
我想这很容易:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
但 中没有Calendar
财产DatePicker
。
有什么办法可以得到那个参考吗?
尝试这个:
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:
始终FindChild
仅在控件将完全加载时使用,否则将找不到它并给出null。在这种情况下,我将这段代码放在ContentRendered
表示Window
窗口的所有内容成功加载的情况下。
清单 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;
}
试试这个代码:
Popup popup = Template.FindName("PART_Popup", this) as Popup;
_calendar = (Calendar)popup.Child;