我需要参考Calendar
in a DatePicker
object.
我想象这很容易:
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
of 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)