我需要在 DatePicker
对象中获取对 Calendar
的引用。
我想象这很容易:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
但 DatePicker
中没有 Calendar
属性。
有什么方法可以获取该引用吗?
最佳答案
试试这个:
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;
}
关于wpf - 如何在 WPF 中的 DatePicker 中获取日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18076210/