1
我需要在DatePicker
對象中引用Calendar
。如何在DatePicker中獲取WPF中的日曆
我想像的那麼容易:
DatePicker datePicker = new DatePicker();
Calendar calendar = datePicker.Calendar;
但在DatePicker
沒有Calendar
財產。
有沒有辦法如何獲得該參考?
我需要在DatePicker
對象中引用Calendar
。如何在DatePicker中獲取WPF中的日曆
我想像的那麼容易:
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
只有當控制將被完全加載,否則將無法找到它,並給空。在這種情況下,我將這段代碼放在Window
的事件ContentRendered
中,它說成功加載了窗口的所有內容。
的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;
爲什麼你通過代碼訪問日曆嗎? –
突出顯示日曆中的日期:http://www.codeproject.com/Tips/547627/Highlight-dates-on-a-WPF-Calendar –