如何在WPF Command中传递整数参数 实现点击月历日期跳转到对应日视图
解决方法
问题根因说明
你原来的命令绑定是失效的:在DataTemplate中直接写{Binding ToDayViewCommand}时,绑定上下文是CurrentMonth.Days集合里的单个Day实例,这个类没有ToDayViewCommand属性,所以实际会触发绑定错误,只是你没注意到输出窗口的提示。
1. 修正XAML绑定
你需要通过RelativeSource向上找到父级ListView的绑定上下文(也就是MonthViewModel实例)拿到命令,同时用CommandParameter传递当前的日期编号:
<ListView ItemsSource="{Binding CurrentMonth.Days}" Grid.Row="1"> <ListView.ItemTemplate> <DataTemplate> <Button Content="{Binding DayNumber}" Grid.Row="1" Height="20" Width="100" Command="{Binding DataContext.ToDayViewCommand, RelativeSource={RelativeSource AncestorType=ListView}}" CommandParameter="{Binding DayNumber}"/> </DataTemplate> </ListView.ItemTemplate> </ListView>
如果想更省后续逻辑,可以直接传整个Day对象,把CommandParameter改成{Binding .}即可。
2. 修正MonthViewModel逻辑
首先修复你原来的两个bug:
CurrentMonth的属性变更通知字符串拼写错误- 直接使用命令传递过来的参数,不需要写死日期编号
public class MonthViewModel : ViewModelBase { private readonly NavigationStore _navigationStore; private Month _currentMonth; public Month CurrentMonth { get { return _currentMonth; } set { _currentMonth = value; // 修正属性名拼写错误 OnPropertyChanged(nameof(CurrentMonth)); } } public void ToDayView(object parameter) { // 直接使用命令传递过来的日期编号 int dayNumber = (int)parameter; var targetDay = CurrentMonth.Days.FirstOrDefault(d => d.DayNumber == dayNumber); if (targetDay != null) { _navigationStore.CurrentViewModel = new DayViewModel(targetDay, _navigationStore); } } public BasicCommand ToDayViewCommand { get; set; } public MonthViewModel(Month currentMonth, NavigationStore navigationStore) { CurrentMonth = currentMonth; _navigationStore = navigationStore; ToDayViewCommand = new BasicCommand(ToDayView); } }
如果你之前选择直接传整个Day对象,ToDayView方法可以简化为:
public void ToDayView(object parameter) { var targetDay = parameter as Day; if (targetDay != null) { _navigationStore.CurrentViewModel = new DayViewModel(targetDay, _navigationStore); } }
不需要额外遍历集合,运行效率更高。
内容的提问来源于stack exchange,提问作者Imightbehigh
相关产品推荐
相关产品推荐

