WPF Calendar Control holding on to the Mouse

后端 未结 4 772
孤独总比滥情好
孤独总比滥情好 2021-01-11 14:20

So I dropped the standard WPF Calendar control on the MainWindow.xaml in a brand new WPF App in VS2010. If I click on a day in the calendar and then try to cli

相关标签:
4条回答
  • 2021-01-11 15:01

    You can change this behavior by subscribing to the calendar's PreviewMouseUp event with a handler like this:

    private void Calendar_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (Mouse.Captured is CalendarItem)
        {
            Mouse.Capture(null);
        }
    }
    
    0 讨论(0)
  • 2021-01-11 15:08

    This code must help

    Calendar.PreviewMouseUp += (o, e) =>
    {
        if (!e.OriginalSource.Equals(Calendar))
        {
            Mouse.Capture(null);
        }
    };
    
    0 讨论(0)
  • 2021-01-11 15:09

    The calendar control is hosted in a popup, and captures the mouse. When you click somewhere else the first time, the capture sends the click to the popup, which, realizing that you've clicked outside of itself, closes. The click therefore does not go to the button.

    You can see the same effect when using a ComboBox. Drop it down, then click on a button. It won't click the button.

    Unfortunately, it's unlikely you can do anything to alter this behavior.

    Edit: More recent versions of .NET make a solution possible. See Eren's answer.

    0 讨论(0)
  • 2021-01-11 15:16

    This is the basis of the code I use to work around both the mouse capture issue and the lack of Click events from child controls. It can probably be simplified further to make the calendar control more directly accessible, but I personally tend to add it into the UserControl.

    class FixedCalendar : UserControl
    {
        public FixedCalendar()
        {
            InitializeComponent();
        }
    
        protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseUp(e);
            if (Mouse.Captured is System.Windows.Controls.Primitives.CalendarItem)
            {
                Mouse.Capture(null);
    
                var element = e.OriginalSource as FrameworkElement;
                if (element != null)
                    element.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            }
        }
    }
    
    <UserControl x:Class="FixedCalendar"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Calendar x:Name="Calendar" />
    </UserControl>
    
    0 讨论(0)
提交回复
热议问题