wpf - 如何在 WPF 中的 DatePicker 中获取日历

标签 wpf calendar datepicker components

我需要在 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/

相关文章:

wpf - 打开文件夹并使用 WPF 突出显示特定文件

c# - Exchange Web 服务和 C# : How to get appointments from shared calendar

GMT +x 地区的 Android 日历全天 Activity 日期关闭一天

grails - Grails:如何在日历插件中禁用日期

jquery - 在 struts 应用程序中使用带有名称而不是 id 的 jQuery 日期选择器

c# - Keybind Shortcuts - 从 MainView 打开其他 View - MVVM

wpf - 降低 WPF 图像控件中的图像分辨率

c# - 以编程方式将枚举类型绑定(bind)到组合框

java - 我如何使用 java.util.Calendar 返回伊斯兰日历?

jquery - 如何选择动态日期选择器实例以便使用 jQuery 扩展它