且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测Silverlight日历控件上何时单击一天

更新时间:2022-02-19 09:59:10

不是一个很干净的解决方案。此外,它没有正确考虑BlackoutDates,因为按钮的IsBlackOut属性也是内部的。我可以手动检查在我的点击事件,但为了我的目的,我不需要支持。

Not a very clean solution. Also, it does not properly take into account BlackoutDates because the IsBlackOut property of the button is also internal. I could manually check against that in my click event, but for my purposes I didn't need to support that.

void CalendarControl_Loaded(object sender, RoutedEventArgs e)
{
    var grid = FindVisualChildByName<Grid>(CalendarControl, "MonthView");
    // Loaded may be called several times before both the grid and day buttons are created
    if (grid != null && grid.Children.OfType<System.Windows.Controls.Primitives.CalendarDayButton>().Any()) 
    {
        // Add our own click event directly to the button
        foreach (var button in grid.Children.OfType<System.Windows.Controls.Primitives.CalendarDayButton>().Cast<System.Windows.Controls.Primitives.CalendarDayButton>())
        {
            button.Click += new RoutedEventHandler(button_Click);
        }
        // We only want to add the event once
        CalendarControl.Loaded -= new RoutedEventHandler(CalendarControl_Loaded);
    }
}

void button_Click(object sender, RoutedEventArgs e)
{
    var button = (System.Windows.Controls.Primitives.CalendarDayButton)sender;
    var date = button.DataContext as DateTime?;
    // The user clicked a date. Close the calendar and do something with it
}

FindVisualChildByName从 http:// pwnedcode。 wordpress.com/2009/04/01/find-a-control-in-a-wpfsilverlight-visual-tree-by-name/

FindVisualChildByName is copied from http://pwnedcode.wordpress.com/2009/04/01/find-a-control-in-a-wpfsilverlight-visual-tree-by-name/