2013-08-06 41 views
1

我需要在DatePicker對象中引用Calendar如何在DatePicker中獲取WPF中的日曆

我想像的那麼容易:

DatePicker datePicker = new DatePicker(); 
Calendar calendar = datePicker.Calendar; 

但在DatePicker沒有Calendar財產。

有沒有辦法如何獲得該參考?

+0

爲什麼你通過代碼訪問日曆嗎? –

+1

突出顯示日曆中的日期:http://www.codeproject.com/Tips/547627/Highlight-dates-on-a-WPF-Calendar –

回答

1

試試這個:

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; 
    } 
0

試試這個代碼:

Popup popup = Template.FindName("PART_Popup", this) as Popup; 

_calendar = (Calendar)popup.Child; 
相關問題