WPF中如何点击BarButton打开日期输入弹窗
实现点击按钮弹出带日期选择器的弹窗并传递日期参数
方案一:使用DevExpress FlyoutDialog实现
1. 调整XAML代码
保留原Bar控件结构,将Command绑定到ViewModel中的对应命令:
<StackPanel> <BarContainerControl> <BarSubItem Content="List"> <BarButtonItem Content="Button" Command="{Binding ShowDatePickerCommand}" /> </BarSubItem> </BarContainerControl> </StackPanel>
2. ViewModel中实现命令与弹窗逻辑
基于MVVM模式实现命令,点击按钮时弹出带DateEdit的FlyoutDialog,获取选中日期后传入HandleStuff方法:
using DevExpress.Mvvm; using DevExpress.Xpf.Core; using DevExpress.Xpf.Editors; using System.Windows; using System.Windows.Input; public class MainViewModel : ViewModelBase { public ICommand ShowDatePickerCommand { get; } public MainViewModel() { ShowDatePickerCommand = new RelayCommand(ExecuteShowDatePicker); } private void ExecuteShowDatePicker() { // 创建日期选择器控件 var dateEdit = new DateEdit { Width = 200, Margin = new Thickness(10), EditValue = DateTime.Now // 默认选中当前日期 }; // 配置并显示FlyoutDialog var flyoutDialog = new FlyoutDialog { Content = dateEdit, Header = "选择日期", Width = 250, Height = 150, Owner = Application.Current.MainWindow }; // 弹窗确认后传递日期参数 if (flyoutDialog.ShowDialog() == true) { if (dateEdit.EditValue is DateTime selectedDate) { HandleStuff(selectedDate); } } } private void HandleStuff(DateTime selectedDate) { // 这里处理选中的日期参数 MessageBox.Show($"选中的日期:{selectedDate:yyyy-MM-dd}"); } }
方案二:自定义Popup控件实现
若不想依赖FlyoutDialog,可使用WPF原生Popup结合DateEdit:
1. XAML中添加Popup
<StackPanel> <BarContainerControl> <BarSubItem Content="List"> <BarButtonItem Content="Button" Command="{Binding ShowCustomDatePopupCommand}" /> </BarSubItem> </BarContainerControl> <!-- 自定义日期选择弹窗 --> <Popup x:Name="DatePickerPopup" Placement="Center" AllowsTransparency="True"> <Border Background="White" BorderBrush="Gray" BorderThickness="1" Padding="10"> <StackPanel> <TextBlock Text="选择日期" Margin="0 0 0 5"/> <DateEdit x:Name="PopupDateEdit" Width="200"/> <StackPanel Orientation="Horizontal" Margin="0 10 0 0" HorizontalAlignment="Right"> <Button Content="确定" Width="60" Margin="0 0 5 0" Click="ConfirmDate_Click"/> <Button Content="取消" Width="60" Click="CancelDate_Click"/> </StackPanel> </StackPanel> </Border> </Popup> </StackPanel>
2. 后台代码处理弹窗逻辑
private void ConfirmDate_Click(object sender, RoutedEventArgs e) { if (PopupDateEdit.EditValue is DateTime selectedDate) { HandleStuff(selectedDate); } DatePickerPopup.IsOpen = false; } private void CancelDate_Click(object sender, RoutedEventArgs e) { DatePickerPopup.IsOpen = false; } // MVVM模式下通过命令控制弹窗显示 public ICommand ShowCustomDatePopupCommand => new RelayCommand(() => DatePickerPopup.IsOpen = true); private void HandleStuff(DateTime selectedDate) { // 处理日期逻辑 }
关键注意点
- 确保ViewModel已绑定到View的DataContext
- 使用DevExpress控件时需引用对应命名空间(
DevExpress.Xpf.Core、DevExpress.Xpf.Editors) - 若之前FlyoutControl使用失败,大概率是未正确设置弹窗内容或未处理关闭后的取值逻辑
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

