如何在 WPF 中的 DatePicker 中获取日历 [英] How to get a Calendar in DatePicker in WPF
本文介绍了如何在 WPF 中的 DatePicker 中获取日历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 DatePicker
对象中获取对 Calendar
的引用.
I need to get reference to a Calendar
in a DatePicker
object.
我想这很容易:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
但 DatePicker
中没有 Calendar
属性.
but there is no Calendar
property in DatePicker
.
有什么方法可以得到那个参考吗?
Is there any way how to get that reference?
推荐答案
试试这个:
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)
));
}
注意:
总是在控件会完全加载的时候才使用FindChild
,否则找不到它并给null.在这种情况下,我将此代码放在 Window
的事件 ContentRendered
中,这表示窗口的所有内容都已成功加载.
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.
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 中的 DatePicker 中获取日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文