2

我需要CalendarDatePicker对象中获取对 a 的引用。

我想这很容易:

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

但 中没有Calendar财产DatePicker

有什么办法可以得到那个参考吗?

4

2 回答 2

2

尝试这个:

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;
    }
于 2013-08-06T10:01:14.540 回答
0

试试这个代码:

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

_calendar = (Calendar)popup.Child;
于 2017-03-17T10:32:13.323 回答