在WPF中单击外部时隐藏日期选择器的日历

rvpgvaaj  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(148)

我正在尝试创建一个定制的约会选择器。传统的日历只有在用户点击日历图标时才会打开。我想实现的是用户无论何时点击文本或图标都可以打开日历。以下是我的代码。一切都按预期进行。唯一的缺点是当用户想关闭日历时,他们必须再次点击红色的Stackpanel。我希望日历消失时,他们点击的日期选择器之外,以及。我尝试为红色Stackpanel添加LostFocus事件,但它不起作用。有人有解决办法吗?我很感激任何帮助。谢谢你
XAML文件:

<DatePicker x:Name="MyDatePicker" 
            SelectedDate="{Binding ApptNotScheduledStartDate}" 
            SelectedDateChanged="DatePicker_SelectedDateChanged" >
    <DatePicker.Template>
        <ControlTemplate TargetType="DatePicker">
            <StackPanel>
                <StackPanel MouseLeftButtonDown="TextBlock_Click" 
                            Orientation="Horizontal" Background="Red"  
                            Height="33" LostFocus="StackPanel_LostFocus">
                    <TextBlock Text="{Binding ApptNotScheduledStartDate, StringFormat='{}{0:MMM dd, yyyy}'}" />
                    <materialDesign:PackIcon Kind="ChevronDown"/>
                </StackPanel>
                <Popup x:Name="PART_Popup" 
                        IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}">
                    <Border BorderBrush="Black" BorderThickness="1" Background="White">
                        <Calendar SelectedDate="{Binding ApptNotScheduledStartDate, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
                    </Border>
                </Popup>
            </StackPanel>
        </ControlTemplate>
    </DatePicker.Template>
</DatePicker>

代码隐藏:

private void TextBlock_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            MyDatePicker.IsDropDownOpen = !MyDatePicker.IsDropDownOpen;
        }

        private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            MyDatePicker.IsDropDownOpen = false;
        }

        private void StackPanel_LostFocus(object sender, RoutedEventArgs e)
        {
            MyDatePicker.IsDropDownOpen = false;
        }

42fyovps

42fyovps1#

作为您尝试的LostFocus方法的替代方案,您可以处理MyDatePickerMouseMove事件并检查鼠标是否在MyDatePicker上:

private void MyDatePicker_MouseMove(object sender, MouseEventArgs e)
{
    Point pt = e.GetPosition((UIElement)sender);

    HitTestResult result = VisualTreeHelper.HitTest(MyDatePicker, pt);

    if (result != null)
        MyDatePicker.IsDropDownOpen = true;
    else
        MyDatePicker.IsDropDownOpen = false;
}

相关问题