如何从DatePicker控件取值并作为参数传递给命令?
解决方案
步骤1:完善ViewModel实现
首先需要实现ICommand的具体实现(比如RelayCommand,WPF无内置该类),同时给ViewModel添加日期属性并实现INotifyPropertyChanged接口以支持数据绑定通知:
1.1 实现RelayCommand
public class RelayCommand : ICommand { private readonly Action<object> _execute; private readonly Func<object, bool> _canExecute; public event EventHandler CanExecuteChanged; public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } public void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } }
1.2 修改MainWindowViewModel
using System.ComponentModel; using System.Windows.Input; public class MainWindowViewModel : INotifyPropertyChanged { private readonly JiraHandler jiraHandler; private DateTime date; // 绑定DatePicker的SelectedDate属性 public DateTime Date { get => date; set { if (date != value) { date = value; OnPropertyChanged(nameof(Date)); } } } public ICommand DateChosen { get; } public ObservableCollection<Issue> Issues { get; private set; } = new ObservableCollection<Issue>(); public MainWindowViewModel(JiraHandler jiraHandler) { this.jiraHandler = jiraHandler; DateChosen = new RelayCommand(ExecuteDateChosen); } private void ExecuteDateChosen(object parameter) { // 可选择使用参数传递的日期,或ViewModel自身的Date属性 DateTime targetDate = parameter != null ? (DateTime)parameter : Date; // 调用JiraHandler加载对应日期数据 var loadedIssues = jiraHandler.LoadIssuesForDate(targetDate); // 更新UI绑定的集合 Issues.Clear(); foreach (var issue in loadedIssues) { Issues.Add(issue); } } // INotifyPropertyChanged接口实现 public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
步骤2:XAML绑定设置
有两种常见绑定方式可选:
方式一:绑定日期到ViewModel属性,命令直接调用属性值
适合需要在ViewModel中持久化该日期,或其他逻辑需复用的场景:
<DatePicker SelectedDate="{Binding Date, Mode=TwoWay}" /> <Button Content="加载数据" Command="{Binding DateChosen}" />
方式二:通过CommandParameter直接传递DatePicker选中值
无需在ViewModel中额外维护日期属性,更轻量化:
<DatePicker x:Name="TargetDatePicker" /> <Button Content="加载数据" Command="{Binding DateChosen}" CommandParameter="{Binding SelectedDate, ElementName=TargetDatePicker}" />
内容的提问来源于stack exchange,提问作者Atlass-
相关产品推荐
相关产品推荐

